In my previous articles, I discussed about MVC (Model-View-Controller) architecture as well as its implementation in details. I am expecting that the reader of this article already understand about the role of Model in an ASP.NET MVC application. Model in MVC is basically a representation of our data structure. So, here in this article, we are going to understand and implement the data annotation technique for applying validation on a model class for an ASP.NET Web API application.
In our ASP.NET Web API article series, we already have created an application that is performing all CRUD (Create, Retrieve, Update, Delete) operations using Web API. Here we will take the same domain model class i.e. “Student.cs” and apply validation on it using data annotation method. In order to better understand with more validation rules, I modified it a bit. So, here is our Model class:
{
[Range(1, 500)]
public int StudentID { get; set; }
[Required]
[MaxLength(10)]
public string FirstName { get; set; }
public string LastName { get; set; }
}
We have applied some validation to our model class properties in the same manner as a database table’s fields have associated validation rules. We have applied the attributes to model properties using System.ComponentModel.DataAnnotations namespace.
Our Model class i.e. Student has following validation rules.
- StudentID value must be between 1 and 500.
- FirstName is also required with maximum length of 10.
- LastName has no associated rule.
We will check the validity of Model against the defined validation rules in controller class i.e. StudentController.
2 {
3 public HttpResponseMessage Post(Student Student)
4 {
5 if (ModelState.IsValid)
6 {
7 // Valid scenario code here…
8 return new HttpResponseMessage(HttpStatusCode.OK);
9 }
. else
. {
. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
. }
. }
. }
Now, when the client will send a POST request in JSON format, its being converted to Student object instance and that instance will be validated against the rules defined in Model class. In above code sample, line # 5, Student instance state is validated and accordingly response is generated.
- A. GET
- B. POST
- C. DELETE
- D. PUT
To further test your ASP.NET Web API skill, Take a Complete FREE Online Test or MCSD Practice Exam: 70-486 (Developing ASP.NET MVC Web Applications). Simply Click Here.
Correct Answer: D
- { “StudentID”:942, “FirstName”:”Imran”, “LastName”:”Ghani” }
- { “StudentID”:100, “FirstName”:”ImraaanAbdul”, “LastName”:”Ghani” }
- { “StudentID”:101, “FirstName”:”Imran”, “LastName”:”Ghani” }
JSON representation 1 & 2 will return with the message “Bad Request….Request is Invalid….” because:
- StudentID value not between the defined validation range (1 to 500).
- FirstName maximum defined length exceeded.
JSON representation 3 is valid and response with status code of 200 will be returned.
Data annotation technique for Model validation is really helpful because it validates data before involving in any further processing. But there are some limitations associated with this approach i.e. Under-Posting and Over-Posting. Follow the post for Limitations to Model Validation in ASP.NET Web API.
- Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer]
28 Lectures, 2.5 Hours Video, Intermediate Level
Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net Web forms. - AngularJS for ASP.NET MVC Developers [Brett Romero]
10 Lectures, 1 hour video, Intermediate Level
The Fastest Way For .NET Developers To Add AngularJS To Their Resume - ASP.NET with Entity Framework from Scratch [Manzoor Ahmad, MCPD | MCT]
77 Lectures, 10 hour video, All Level
Latest approach of web application development - Comprehensive ASP.NET MVC [3D BUZZ]
34 lectures, 14 Hours Video, All Levels
From zero knowledge of ASP.NET to deploying a complete project to production.
More You Must Read about ASP.NET MVC & Related
- ASP.NET MVC3 Vs MVC4 Vs MVC5 Vs MVC6
- 4 Simple Steps to Create your First ASP.NET MVC5 Application
- Understanding ASP.NET MVC Application Life Cycle
- How Routing works in ASP.NET MVC?
- All you need to Know about Controllers and Action Methods in ASP.NET MVC
- Practical Example to learn Scaffolding in ASP.NET MVC
- How to use AJAX in ASP.NET MVC Application?
- Insight of ASP.NET MVC Authorize attribute
- Building ASP.NET MVC5 Application with Entity Framework 6
- Understanding Model-First Approach in ASP.NET MVC with Entity Framework
- ASP.NET View Engine Vs Razor View Engine
- ViewBag Vs ViewData Vs TempData Vs Session
- How to use Model to Pass data to View in ASP.NET MVC?
- Understanding Partial View in ASP.NET MVC
- ASP.NET MVC Helpers – A MUST KNOW
- 2 simple ways to create Custom HTML Helpers in ASP.NET MVC
- All you need to know to pass Exam: 70-486 (Developing ASP.NET MVC Web Applications)
- Free Practical Guide to ASP.NET Web API
- Difference between WCF and ASMX web service
- WCF Hosting (Console | Windows Service)
Top 10 Interview Questions and Answers Series:
- Top 10 ASP.NET AJAX Interview Questions
- Top 10 WCF Interview Questions
- Comprehensive Series of WCF Interview Questions
- Top 10 HTML5 Interview Questions
- Top 10 ASP.NET Interview Questions
- Comprehensive Series of ASP.NET Interview Questions
- Top 10 ASP.NET MVC Interview Questions
- Top 10 ASP.NET Web API Interview Questions