在一个 MVC 项目中,我有一个具有(比方说)10 个属性的类,都是必需的。在用户选择的情况下,我必须验证一次只有 3 个属性,其他时间验证所有属性。
这些是我的 Patient 类的属性:
[Required(ErrorMessage = "Last Name is required")]
[StringLength(50)]
public string responsibleLastName;
[Required(ErrorMessage = "First Name is required")]
[StringLength(50)]
public string responsibleFirstName;
[Required(ErrorMessage = "Address is required")]
[StringLength(50)]
public string responsibleAddressLine1;
[Required(ErrorMessage = "City is required")]
[StringLength(50)]
public string responsibleCityName;
[Required(ErrorMessage = "State is required")]
[StringLength(2)]
public string responsibleStateCode;
[Required(ErrorMessage = "Zip Code is required")]
[StringLength(10)]
public string responsiblePostalZoneOrZIPCode;
[Required(ErrorMessage = "Birth Date is required")]
public DateTime responsibleBirthDate;
[Required(ErrorMessage = "Gender is required")]
public string responsibleGenderCode;
[Required(ErrorMessage = "Home Phone is required")]
[StringLength(10)]
public string responsibleHomePhone;
在保存之前,在控制器中我正在进行验证:
if (firstCondition) //partial validation
{ if (!ModelState.IsValidField("responsibleLastName"))
{
ModelState.AddModelError("responsibleLastName", "Last Name is required");
isOK = false;
}
//... and 2 more validation
//finally I check the isOK value
if (!isOK)
return PartialView("firstCondition", model);
else
// do something
}
else { //validate all the properties from the model
if (!ModelState.IsValid)
return PartialView("secondCondition", model);
else
//do something
}
在第一种情况下,我的消息对于这 3 个属性 + 类的所有错误消息都是重复的。
ModelState.IsValidField 正在调用 Model.IsValid 并获取每个属性的 ModelValidationResult 列表,然后检查我想要的字段的结果?为什么消息重复?
我想使用模型验证工具,所以我不想手动验证值
//NOT
if (!model.responsibleLastName == "")
{
ModelState.AddModelError("responsibleLastName", "Last Name is required");
isOK = false;
}
先感谢您。