Model Validation In ASP.NET Web API Using MVC

Today, I will explain how to validate Web API using model validation or data annotation on the client side. We can perform model validation in MVC in an easy way. In API, when sending the request by the client or user to web API, then before doing the next process, it checks the empty validation and handles the validation error using data annotation in WEB API.

So now, let us see step by step.

Step 1

First, we will add a Web API project. For that, open Visual Studio -> File -> Select ASP.NET Web Application -> Select API and click OK.

Step 2

After that, we will add a database using model first approach. So, for this, go to the model folder and then right click -> Select Add option -> New Item -> Data (Left Panel) -> Choose ADO .NET Entity Data Model - > Click Ok -> Select EF Designer from database -> Next -> Select New Connection -> and give the server name and user id and password of your SQL Server

ASP.NET

After that click on test connection -> Ok ->Ok -> Select Next -> Expand the tables and check our table -> after that Click Finish button

Step 3

After finishing the second step now we will go to model folder and select our class. Here I am using RegisterUser(Demo) class.

  1. namespace WebApiValidation.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.ComponentModel.DataAnnotations;  
  6.       
  7.     public partial class RegisterUser  
  8.     {  
  9.         public int UserID { get; set; }  
  10.         [Required(ErrorMessage = "Please enter User Name")]  
  11.         public string UserName { get; set; }  
  12.          [Required(ErrorMessage = "Please enter Password")]  
  13.         public string Password { get; set; }  
  14.          [Required(ErrorMessage = "Please enter Email Id")]  
  15.         public string EmailID { get; set; }  
  16.         public Nullable<System.DateTime> CreateOn { get; set; }  
  17.     }  
  18. }  

After that we will go to our solution and add a Filter folder and right click filter folder and add a class

ASP.NET

After adding ValidateModelRegister Class now we are going to inherit from ActionFilterAttribute class inside that we are going to write our custom logic like as shown below

  1. using System.Linq;  
  2. using System.Net;  
  3. using System.Net.Http;  
  4. using System.Web.Http.Controllers;  
  5. using System.Web.Http.Filters;  
  6. using System.Web.Http.ModelBinding;  
  7.   
  8. namespace WebApiValidation.Filter  
  9. {  
  10.     public class ValidateModelRegister : ActionFilterAttribute  
  11.     {  
  12.     }  
  13. }  

After inheriting from ActionFilterAttribute now let us implement OnActionExecuting method of it. In this method we are going check if the Model which is posted is valid or not; if not then we are going to CreateErrorResponse as shown below.

  1. using System.Linq;  
  2. using System.Net;  
  3. using System.Net.Http;  
  4. using System.Web.Http.Controllers;  
  5. using System.Web.Http.Filters;  
  6. using System.Web.Http.ModelBinding;  
  7.   
  8. namespace WebApiValidation.Filter  
  9. {  
  10.     public class ValidateModelRegister : ActionFilterAttribute  
  11.     {  
  12.         public override void OnActionExecuting(HttpActionContext actionContext)  
  13.         {  
  14.             if (actionContext.ModelState.IsValid == false)  
  15.             {  
  16.                 actionContext.Response = actionContext.Request.CreateErrorResponse(  
  17.                     HttpStatusCode.BadRequest, actionContext.ModelState);  
  18.             }  
  19.         }  
  20.     }  
  21. }  

Now we will add a API controller so right click controller folder -> add ->Controller ->Select API Controller

  1. [RoutePrefix("api/UserReg")]   
  2.     public class RegisterAPIController : ApiController  
  3.     {  
  4.     }  

After that we will add an action method for posting the data. Now that we have implemented OnActionExecuting method let’s apply it on our post method.

  1. [RoutePrefix("api/UserReg")]   
  2.     public class RegisterAPIController : ApiController  
  3.     {  
  4.   
  5.         [HttpPost]  
  6.         [Route("Register")]  
  7.         [ValidateModelRegister]  
  8.         public string RegisterUser(RegisterUser data)  
  9.         {  
  10.             MKDBEntities objEntity = new MKDBEntities();  
  11.             data.CreateOn = System.DateTime.Now;  
  12.             objEntity.RegisterUsers.Add(data);  
  13.           int i= objEntity.SaveChanges();  
  14.             if(i > 0)  
  15.             {  
  16.                 return "Successfully inserted ";  
  17.             }  
  18.             else  
  19.             {  
  20.                 return "Insertion faild";  
  21.             }  
  22.   
  23.   
  24.         }    
  25.     }  

Step 4

Now we have completed the API part so now we are going to add an MVC controller for consuming API or posting in API and creating an action method and add view.

ASP.NET
  1. public class MVCController : Controller  
  2.     {  
  3.         // GET: MVC  
  4.         public ActionResult Register()  
  5.         {  
  6.             return View();  
  7.         }  
  8.     }  

After that we will design our view page

  1. <h2>Registration Form</h2>  
  2. <div>  
  3.     <form>  
  4.          
  5.         <table>  
  6.             <tr>  
  7.                 <td>User Name : </td>  
  8.                 <td>  
  9.                     <input type="text" id="txtUserName" class="form-control" />  
  10.                      
  11.                 </td>  
  12.             </tr>  
  13.             <tr>  
  14.                 <td>Password : </td>  
  15.                 <td>  
  16.                     <input type="password" id="txtPassword" class="form-control" />  
  17.                 </td>  
  18.             </tr>  
  19.             <tr>  
  20.                 <td>Email ID : </td>  
  21.                 <td>  
  22.                     <input type="email" id="txtEmail" class="form-control" />  
  23.                      
  24.                 </td>  
  25.             </tr>  
  26.             
  27.            
  28.             <tr>  
  29.                 <td></td>  
  30.                 <td>  
  31.                     <input type="button" value="Register" id="btnRegister" class="btn btn-primary" />  
  32.                 </td>  
  33.             </tr>  
  34.         </table>  
  35.     </form>  
  36.     <div id="DivMessage">  
  37.   
  38.     </div>  
  39. </div>  

Now we will write Ajax method for posting user registration details.

  1. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  2. <script type="text/javascript">  
  3.   
  4.     $(document).ready(function () {  
  5.   
  6.         $("#btnRegister").click(function () {  
  7.             $("#DivMessage").empty();  
  8.             var data = {  
  9.                 UserName: $("#txtUserName").val(),  
  10.                 Password: $("#txtPassword").val(),  
  11.                 EmailID: $("#txtEmail").val()  
  12.             }  
  13.   
  14.             $.ajax({  
  15.                 url: "/api/UserReg/Register",  
  16.                 type:"POST",  
  17.                 data:  data,  
  18.                 contenttype: "application/json;utf-8",  
  19.                 datatype:"json"  
  20.             }).done(function (resp) {  
  21.                 $("#DivMessage").append('<table class="table"><tr><td style="color:green" width="50px">' + resp + '</td></tr>');  
  22.             }).error(function (err) {  
  23.                  
  24.                 var validationErrors = $.parseJSON(err.responseText);  
  25.                 $.each(validationErrors.ModelState, function (i, valText) {  
  26.   
  27.                     $("#DivMessage").append('<table class="table"><tr><td style="color:red" width="50px">' + valText + '</td></tr>');  
  28.   
  29.                 });  
  30.             });        
  31.   
  32.         });  
  33.     });  
  34.   
  35. </script>  

How does it work?

Here when user submits blank details then the request goes to Action method  of API controller. Before  the method is executed the ActionFilter on that method gets executed as ActionFilter and checks if model is valid or not. If it isn't valid then it will give error response of status code 400 and a message. In Ajax we used two methods  -- done and error. When we send blank user details to the field the Ajax Post method gives an invalid message because it does not have any data, then it sends 400 bad responses.

$.parseJSON(err.responseText);

After getting an error we are going to iterate on the object and append a table for displaying the error message and we will append this table with a DIV tag.

  1. $.each(validationErrors.ModelState, function (i, valText) {  
  2.                     $("#DivMessage").append('<table class="table"><tr><td style="color:red" width="50px">' + valText + '</td></tr>');  
  3.                 });  

Now see the output,

ASP.NET
ASP.NET

If it is valid then it will give success message

ASP.NET

I hope this article was helpful for you.