我有一个自定义数据验证属性我创建,以确保用户输入的密码是相同的,但从不调用IsValid.
public class IsSameAsAttribute : ValidationAttribute { public String TargetProperty { get; set; } private readonly object _typeId = new object(); public IsSameAsAttribute(string targetProperty) { TargetProperty = targetProperty; } public override bool IsValid(object value) { return false; //Type objectType = value.GetType(); //bool isValid = false; //PropertyInfo[] neededProperties = // objectType.GetProperties().Where(propertyInfo => propertyInfo.Name == TargetProperty).ToArray(); //return isValid; } public override object TypeId { get { return _typeId; } } }
它适用的数据模型:
public class RegistrationData { [required(ErrorMessage = "First Name required")] [StringLength(100,ErrorMessage = "First Name must be 100 characters or less.")] public String FirstName { get; set;} [required(ErrorMessage = "Last Name required")] [StringLength(100,ErrorMessage = "Last Name must be 100 characters or less.")] public String LastName { get; set; } [required(ErrorMessage = "Email is required")] [StringLength(200,ErrorMessage = "Email must be 200 characters or less.")] [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",ErrorMessage = "Valid Email Address is required.")] public String Email { get; set; } [required(ErrorMessage = "Password is required")] public String Password { get; set; } [IsSameAs("Password")] public String PasswordRepeat { get; set; } [required(ErrorMessage = "Division is required")] public String Division { get; set; } }
控制器从哪里调用:
[HttpPost] public ActionResult ValidationDemo(RegistrationData model) { if (ModelState.IsValid) { return Redirect("/"); } return View(model); }
所有“开箱即用”验证都能正常运行,只是我的自定义验证没有被调用.在进行调试时,我发现它是在调用构造函数时实例化的,但是在IsValid上设置的断点永远不会被命中.
发生了什么,我该如何解决?
UPDATE
好吧,我摆弄了一些,如果我在我的控制器中调用TryUpdateModel(模型),它最终会调用IsValid.所以这对我来说意味着我的自定义属性没有被“注册”任何运行MVC 2中的验证.有没有办法解决这个问题?
[HttpPost] public ActionResult ValidationDemo(RegistrationData model) { TryValidateModel(model); // <--- *** Added this line and it "works" if (ModelState.IsValid) { return Redirect("/"); } return View(model); }