How can I centralize modelstate validation in asp.net mvc using action filters?

后端 未结 4 1856
一生所求
一生所求 2020-12-05 01:11

I write this code in several places and always repeat this logic:

public ActionResult MyMethod(MyModel collection)
{
    if (!ModelState.IsValid)
    {
              


        
4条回答
  •  天涯浪人
    2020-12-05 01:16

    public class ValidateModelStateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {              
                context.Result = new ViewResult();
            }
        }
    }
    

提交回复
热议问题