我的页面上有3行用于输入成就。我希望ViewModel状态是有效的,即使只有1行被填充。现在,只有当我填充了所有3行时,模型状态才有效。
我必须为此创建多个构造函数吗?
public int AchievementsRank1 { get; set; }
public string AchievementsEvent1 { get; set; }
public int AchievementsRank2 { get; set; }
public string AchievementsEvent2 { get; set; }
public int AchievementsRank3 { get; set; }
public string AchievementsEvent3 { get; set; }
public EditProfileViewModel()
{
}
public EditProfileViewModel(string username, int achievementsR1, string achievementsE1, int achievementsR2, string achievementsE2, int achievementsR3, string achievementsE3, string freetext, string social)
{
this.Username = username;
this.AchievementsRank1 = achievementsR1;
this.AchievementsEvent1 = achievementsE1;
this.AchievementsRank2 = achievementsR2;
this.AchievementsEvent2 = achievementsE2;
this.AchievementsRank3 = achievementsR3;
this.AchievementsEvent3 = achievementsE3;
this.Freetext = freetext;
this.SocialURL = social;
}
[ValidateAntiForgeryToken]
public IActionResult Index([Bind("Username,AchievementsRank1,AchievementsEvent1,AchievementsRank2,AchievementsEvent2,AchievementsRank3,AchievementsEvent3,Freetext,SocialURL")] EditProfileViewModel edit)
{
if (ModelState.IsValid)
{
ProfileDTO dto = CreateDtoFromInput(edit);
//commands.SaveNewProfile(dto);
Profile prof = new Profile(dto);
return View("Profile", prof);
}
else
{
return View(edit);
}
}
ViewModel验证通常集中在1个属性上。
您可以创建一个自定义注释,并"组合"多个属性,创建自己的验证规则。正如您所读到的,这种方法使用注释而不是bind(
。
我还建议将许多属性更改为一个对象作为ViewModel,它看起来会更干净。
public class Movie
{
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Title { get; set; }
[CustomAnnotation(x,y,z)]
[StringLength(1000)]
public string Description { get; set; }
[Range(0, 999.99)]
public decimal Price { get; set; }
[Required]
public Genre Genre { get; set; }
public bool Preorder { get; set; }
}
看看这里的例子https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.0