Search code examples
c#.net-coreasp.net-core-2.1asp.net-mvc-filters

Validate a model with filter Attribute


I am practicing about validations in attributes for DRY reasons but I get some examples for Web Api and I do not know if there is a way to return a View with the invalid data and modelstate errors instead of BadRequestObjectResult used in API.

I have read the official documentation about it but I do not understand how it is implemented in the case of a view.

I am using a basic model with 2 inputs to add data in EF Core Entity to test this attribute filter. My objective is get something generic for this case because I understand it for Web Api.

Thanks in advance for any help you can give me.

I want to change this in the IActionResult:

if(!ModelState.IsValid)
    return View(ModelState)

to something like this attribute class:

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            // I know that this line indicates a BadRequestObjectResult
            // but I don't know how to returning like view if
            // the Web App use razor pages

            context.Result = new BadRequestObjectResult(context.ModelState);
        }

    base.OnActionExecuting(context);
}

This is the actual response with the example (But I want to use the MVC pages to return the errors and the model data):

{ "LastName":["The LastName field is required."],"FirstName":["The FirstName"]}

Solution

  • If you are creating Validation filter, you do not need to do anything inside your ValidateModelAttribute. you just need to check ModelState.IsValid, so it will work globally and it will return view same as you write it on controller's action.

    Without writing any extra code, it will return your view with error.

     [ValidateModel]
     public IActionResult Index(Test t)
     {
        return View(t);
     }
    
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
    
            }
            base.OnActionExecuting(context);
        }
    
    }