user1068477
user1068477

Reputation:

ASP.NET MVC Validation and Model Properties, what happens first?

I have a model with properties and validators (annotations) above most of them validating this or that.

Does a validator use the Model Property or does it use the raw value sent by the POST? In other words, are Properties set first, then validation occurs, or does validation occur first, then the Properties are set (if validation returns no error)?

Upvotes: 0

Views: 361

Answers (1)

pkatsourakis
pkatsourakis

Reputation: 1082

  1. The Web API will receive the raw data
  2. Raw data is converted to an object instance (so properties are set first)
  3. Validate the object against the validation attributes

You can check to see if your model was valid or not in the controller like so:

public class ProductsController : ApiController
    {
        public HttpResponseMessage Post(Product product)
        {
            if (ModelState.IsValid)
            {
                // Do something with the product (not shown).

                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }
    }

More info: Model Validation in ASP.NET

Upvotes: 1

Related Questions