Model in MVC is a representation of our data structure so we need to validate the input data by applying validation on model. Here for that purpose we will implement the data annotation technique for applying model validation in Asp.NET Web API application.
In order to use the Data Annotations Model in an ASP.NET MVC application, we first need to add 2 references in the application:
1. Microsoft.Web.Mvc.DataAnnotations.dll assembly
2. System.ComponentModel.DataAnnotations.dll assembly
For example, We will use a model class like Student and apply validation on it using annotation. For that we need to use or import System.ComponentModel.DataAnnotations namespace. We will apply the different validate attributes to model class properties eg.
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Student { [Required] public int StudentID { get; set; } [Required] [MaxLength(10)] public string FirstName { get; set; } public string LastName { get; set; } [Required] public string ClassName { get; set; } } |
We can check the validity of Model against the defined validation rules in controller class by using ModelState.IsValid i.e.
1 2 3 4 5 6 7 8 9 | if (ModelState.IsValid) { return new HttpResponseMessage(HttpStatusCode.OK); } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } |
Now, when the client will send a POST request in JSON format, it will be converted to Student object instance and will be validated against the model rules.
If we send the data like :
1 | { "StudentID":142, "FirstName":"Sumrin", "LastName":"Kaur" } |
This request will give us the validation error for ClassName and return the response with the message “Bad Request….Request is Invalid….” because it is required field which is not supplied.
In this way, there are many other annotation attributes for validating the model properties by using ComponentModel.DataAnnotations namespace:
Range – Enables you to validate whether the value of a property falls between a specified range of values.
ReqularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.
Required – Enables you to mark a property as required.
StringLength – Enables you to specify a maximum length for a string property.
Validation – The base class for all validator attributes.
Like this, Model validation in ASP.Net Web API application is very easy to understand and implement.