ASP.NET MVC: Is Data Annotation Validation Enough?

后端 未结 5 839
暗喜
暗喜 2020-12-13 02:15

I\'m using the Data Annotation validation extensively in ASP.NET MVC 2. This new feature has been a huge time saver, as I\'m now able to define both client-side validation

5条回答
  •  既然无缘
    2020-12-13 03:12

    I paired xVal with DataAnnotations and have written my own Action filter that checks any Entity type parameters for validation purposes. So if some field is missing in the postback, this validator will fill ModelState dictionary hence having model invalid.

    Prerequisites:

    • my entity/model objects all implement IObjectValidator interface which declares Validate() method.
    • my attribute class is called ValidateBusinessObjectAttribute
    • xVal validation library

    Action filter code:

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        IEnumerable> parameters = filterContext.ActionParameters.Where>(p => p.Value.GetType().Equals(this.ObjectType ?? p.Value.GetType()) && p.Value is IObjectValidator);
        foreach (KeyValuePair param in parameters)
        {
            object value;
            if ((value = param.Value) != null)
            {
                IEnumerable errors = ((IObjectValidator)value).Validate();
                if (errors.Any())
                {
                    new RulesException(errors).AddModelStateErrors(filterContext.Controller.ViewData.ModelState, param.Key);
                }
            }
        }
    }
    

    My controller action is defined like this then:

    [ValidateBusinessObject]
    public ActionResult Register(User user, Company company, RegistrationData registrationData)
    {
        if (!this.ModelState.IsValid)
        {
            return View();
        }
        ...
    }
    

提交回复
热议问题