I see some code that for model validation uses:

 [ValidateModel]

and other code such as a sample WebAPI using this for model validation:

  if (!ModelState.IsValid)
  {
     return BadRequest(ModelState);
  }

Can anyone explain what is the difference and why for example would the sample WebAPI apps from Microsoft not just use the [ValidateModel]?

1 Answers

5
user2771704 On Best Solutions

Are you sure that you have [ValidateModel] attribute out of the box? Because according to this link it is custom attribute that helps make code a little bit cleaner, because you could omit ModelState.IsValid statement in the controller, because if action implemented its Model data is already valid. I browsed the internet and all [ValidateModel] implementations have similar ModelState.IsValid code statement:

public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }

I am not sure, but I think, because [ValidateModel] is custom attribute, which needs additional space for explanation and implementation, so most tutorials prefer out of the box ModelState.IsValid.