Asp.net mvc MVC部分验证(ModelState.IsValid与ModelState.IsValidField)
在一个MVC项目中,我有一个包含(比方说)10个属性的类,所有属性都是必需的。在用户选择的情况下,我必须一次只验证3个属性,其他时间验证所有属性 这些是我的类患者属性:Asp.net mvc MVC部分验证(ModelState.IsValid与ModelState.IsValidField),asp.net-mvc,asp.net-mvc-3,validation,Asp.net Mvc,Asp.net Mvc 3,Validation,在一个MVC项目中,我有一个包含(比方说)10个属性的类,所有属性都是必需的。在用户选择的情况下,我必须一次只验证3个属性,其他时间验证所有属性 这些是我的类患者属性: [Required(ErrorMessage = "Last Name is required")] [StringLength(50)] public string responsibleLastName; [Required(ErrorMessage = "First Name is req
[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;
在保存之前,我在controller中进行验证:
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个属性的my消息与类的所有错误消息都是重复的
ModelState.IsValidField正在调用Model.IsValid,并正在获取每个属性的ModelValidationResult列表,然后检查所需字段的结果?为什么邮件会重复
我想使用模型验证工具,所以我不想手动验证这些值
//NOT
if (!model.responsibleLastName == "")
{
ModelState.AddModelError("responsibleLastName", "Last Name is required");
isOK = false;
}
提前谢谢。您可以按照本博客中的指定,使用自定义的
RequiredIf
验证属性。只是一个简短的问题,为什么要在模型中验证两次一次在控制器中验证一次我想ModelState.IsValidField(“responsibleLastName”)只是在检查模型中的注释。正如我所说,我不想手动验证,如果我使用ModelState.IsValid会检查所有字段,即使我只需要3个字段。基本上,只要你像对所有字段那样对模型进行验证,使所有字段都成为必需的,验证就会自动绑定到你的视图中,如果您假设您不想对其中一些进行验证,那么从模型中删除required,只验证您认为在客户端可能需要的那些,或者验证方式感谢您的响应,但这个示例是我所拥有的一个最低限度的示例。我有一个超过10个属性的模型,另外我还想使用不引人注目的客户端验证,这可以使用元数据的注释。是的,我只会使用客户端验证,但根据您提供的示例(如Lastname),您在模型中验证了两次,在控制器中验证了一次