I tried to add custom validator for ViewModel class:
[Serializable]
public class UserViewModel : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
yield return new ValidationResult("Fail this validation");
}
}
Unfortunately this is not triggered when Action 开发者_如何学JAVAmethod gets called, e.g.
[HttpPost]
public ActionResult Edit(UserViewModel user)
How can I add custom validation logic? ValidationAttribute does not provide easy enough solution. I am unable to find clear information on MVC2 validation mechanisms.
IValidatableObject is not supported in ASP.NET 2.0. Support for this interface was added in ASP.NET MVC 3. You could define a custom attribute:
[AttributeUsage(AttributeTargets.Class)]
public class ValidateUserAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
UserViewModel user = value as UserViewModel;
// TODO: do some validation
ErrorMessage = "Fail this validation";
return false;
}
}
and then decorate your view model with this attribute:
[Serializable]
[ValidateUser]
public class UserViewModel
{
}
Your syntax looks right. The validation isn't "triggered" until you try to validate your model. Your controller code should look like this
[HttpPost]
public ActionResult Edit(UserViewModel user)
{
if(ModelState.IsValid)
{
// at this point, `user` is valid
}
// since you always yield a new ValidationResult, your model shouldn't be valid
return View(vm);
}
精彩评论