ASP.NET MVC Automatic Model Validation

often see this code

image

Write the verification model in the controller, and write each action that needs to be verified.... I'll ask you if you're bothered~

It can be handled automatically by the action interception mechanism of ASP.NET MVC.

1 Create a new validation model

Add using System.ComponentModel.DataAnnotations; reference

 public class Student
    {
        public int Id { get; set; }
        [Required(ErrorMessage= "Name cannot be empty" )]
         public  string Name { get; set; }
        [Range(0,150,ErrorMessage= "Age is invalid" )]
         public  int Age { get; set; }
    }

 

2 Create a new action interception

ModelValidateAttribute

public class ModelValidateAttribute:ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var viewData = filterContext.Controller.ViewData;
            if (!viewData.ModelState.IsValid)
            {
                var errorMessage = "";
                foreach (var key in viewData.ModelState.Keys)
                {
                    var state = viewData.ModelState[key];
                    if (state.Errors.Any())
                    {
                        errorMessage = state.Errors.First().ErrorMessage;
                        break;
                    }
                }
                // ajax directly returns the error validation result 
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult
                    {
                        Data = new { success = false, error = errorMessage },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else {
                    //filterContext.Result = new ViewResult
                    //{
                    //    ViewData = viewData,
                    //    TempData = filterContext.Controller.TempData
                    //};
                   filterContext.Result = new ContentResult() { Content = errorMessage };

                  // throw new Exception(string.Format("Parameter exception:{0}",errorMessage));
                }
            }

            base.OnActionExecuting(filterContext);
        }
       
    }

 

Register in global filter

 public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new JsonRequestBehaviorAttribute());
            filters.Add(new ModelValidateAttribute());
        }
    }

 

参考bolg:http://benfoster.io/blog/automatic-modelstate-validation-in-aspnet-mvc

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325958357&siteId=291194637