Asp.Net Web API Model Validations using Data Annotations in Asp.Net MVC

As both WebAPI and MVC are built on the same ASP.NET framework has most things in common. In asp.net MVC, there are various types of validations such as Data Annotations, Filters used to validate user Authentication & Authorization, and data entered by users the same way in Web API. Also, we will use Data Annotations, Filters to validate that is provided by the ASP.NET framework.

 

In a previous tutorial, we learned how to create Web API (ASP.NET Web API with ASP.NET MVC). We are going to apply validation to the same project we already created. We need to validate the UserComment textbox, which must not be blank before we Add a Comment. We are using asp.net web API to insert data in the database and display data. Following is the snapshot of asp.net web API, which we already created in the previous example create web API in asp.net MVC.

 

output of create asp.net web api in asp.net mvc application

 

Let’s look at how the asp.net MVC project structure looks like, which we had created earlier.

 

Adding new comments class file in asp.net web api application

 

Let’s look at the Comments model that we created previously before moving forward. If you observe, we applied Data Annotations attributes to the model. We want UserComment to be mandatory before adding comments for that. We applied Required Attributes to UserComment Property.

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

using System.Linq;

using System.Web;

 

namespace DemoWebAPI.Models

{

[Table("Comment")]

public class Comment

{

[Key]

public int CommentID { get; set; }

[Required(ErrorMessage = "Please enter UserComment")]

public string UserComment { get; set; }

[ScaffoldColumn (false)]

public DateTime? Commentdate { get; set; }

}

}

 After adding the required attributes with ErrorMessage to the UserComment property, we will add Action Filter to our Project.

Adding New Folder with name Filter to project

Before starting with adding ActionFilter, let's go through the definition of ActionFilter attributes in asp.net mvc. Sometimes we want some logic to check before an action method is called or after an action method is executed. To support this kind of situation, ASP.NET MVC provides action filters.

 

We will add a new folder to the project with the name “Filter” and add ActionFilter. To add a filter, right-click on Project [DemoWebAPI], then from list select Add à inside that select New Folder, give the name “Filter”.

 

Add new folder in asp.net web api application

 

After adding a folder with the name "filter" in asp.net mvc, our application folder structure will be shown below.

 

After adding filter folder in asp.net mvc application

 

After adding the folder now, we will add a public class with Name ValidateModelComment in Filter Folder. For adding public class [ValidateModelComment], right-click on Filter Folder then from list select Add à inside that select Class.

 

Adding new class file to filter folder in asp.net mvc web api application

 

After selecting a class, a new dialog will pop up with the name Add New Item. From the list of Templates, choose a class Template and Name it to validateModelComment.cs.

 

give name to class file in asp.net mvc application

 

After adding ValidateModelComment class, we will inherit from ActionFilterAttribute class inside that we will write our custom logic like as shown below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace DemoWebAPI.Filter

{

public class ValidateModelComment : ActionFilterAttribute

{

 

}

}

After inheriting from ActionFilterAttribute, let’s implement the OnActionExecuting method of it. In this method, we are going to check the Model that is posted is valid or not. If not, then we will call it using CreateErrorResponse like as shown below.

 

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http.Controllers;

using System.Web.Http.Filters;

using System.Web.Http.ModelBinding;

 

namespace DemoWebAPI.Filter

{

public class ValidateModelComment : ActionFilterAttribute

{

public override void OnActionExecuting(HttpActionContext actionContext)

{

if (actionContext.ModelState.IsValid == false)

{

actionContext.Response = actionContext.Request.CreateErrorResponse(

HttpStatusCode.BadRequest, actionContext.ModelState);

}

}

}

}

Now we have implemented the OnActionExecuting method. Let’s apply it ApiController [ValuesController] post method we have created earlier.

 

Applying ActionFilter to Post Method of ValuesController in asp.net mvc web api application

 

After adding ActionFilterAttribute, we will get an error message in response when the field is empty. We need to handle that in jquery Ajax Post Method when we post data, and the textbox is empty will return Responses with 404 status code.

Handling error in Jquery Ajax Post Method

The code which is in red mark is newly added. If any user submits a blank comment, the request goes to ValuesController Post Method [POST api/values]. Before the method is executed, the ActionFilter on that method gets executed as ActionFilter and check model is valid or not. If not, then it will create an error response of status code 400.

 

Action filter error for invalid data in asp.net mvc web api application

 

After that, this response is sent to the browser from the server along with statusCode. In Ajax, we have a parameter called statusCode that we will use to handle the error. When we sent a blank Usercomment field, the Ajax Post method becomes invalid because it does not have any data, then it sends 400 bad responses.

 

After getting 400 bad responses error, we will iterate object and append to Error to Div tag for a little bit of formatting we have added HTML tables to display Error.

 

<div id="DivErrors">

</div>

If your status code is not 400 then it will execute success part. 

 

Displaying code snippet which display error by receiving response in asp.net mvc web api

 

Following is the code snippet of the PostData() function.

 

<script type="text/javascript">

function PostData() {

$("#DivErrors").empty();

var Commenta = { "UserComment": $("#UserComment").val() };

$.ajax({

type: "POST",

data: Commenta,

url: '@Url.Action("Post", "api/values")',

success: function (data) {

GetData();

},

statusCode: {

400: function (response) {

var validationErrors = $.parseJSON(response.responseText);

$.each(validationErrors.ModelState, function (i, ival) {

$("#DivErrors").append('<table class="table"><tr><td width="50px">' + ival + '</td></tr><div style="margin-top: 2px"></div>');

});

}

}

});

}

</script>

After making changes, save and run your application.

 

Accessing view using asp.net web api in asp.net mvc application

 

Now don’t add any User comment and click on the Add comment button when the user submits a blank comment, the request goes to ValuesController Post Method [POST api/values] before the method executed the ActionFilter on that method gets executed as ActionFilter will check model is valid or not if not then it creates Error response of Status code 400.

 

Debug model of action filter in asp.net mvc web api application

 

Following is the response we get when UserComment is blank and to get this open developer tool of Google chrome in which we are getting status code 400 bad request errors.

 

Source view of Request and Response while posting data in asp.net mvc web api validation application

 

After getting an error response, we iterate error to append the error to the div tag.

 

Debugging mode of Ajax method when Status Code is 400 in asp.net mvc web api validation example

 

Finally, we are displaying the error below “Please enter UserComment”.

 

Final output displaying error when UserComment is empty in asp.net mvc web api validation example

 

This is how we can implement validations with asp.net web API in asp.net mvc application.