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

  Total Views : 1473
  Comments : 0
 
  Keywords : Validate content in asp.net web api using data annotations, filters in asp.net mvc with example, Asp.net web api model validations in mvc using data annotations, Asp.net web api validaitions

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

 

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

 

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

 

Let’s have a look on 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 have look on Comments model which we created previously before moving forward if you observe we applied Data Annotations attributes to model. We want UserComment to be mandatory before add comment 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 required attributes with ErrorMessage to UserComment property now we are going to add Action Filter to our Project.

Adding New Folder with name Filter to project

Before starting with adding ActionFilter let's go through 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 are going to add new folder to project with name “Filter” within that we are going to add ActionFilter. For adding filter just right click on Project [DemoWebAPI] then from list select Add à inside that New Folder an then  name to “Filter

 

Add new folder in asp.net web api application

 

After adding folder with name "filter" in asp.net mvc our application folder structure will be like as shown below

 

After adding filter folder in asp.net mvc application

 

After adding folder now we are going to add a public class with Name ValidateModelComment in Filter Folder. For adding public class [ValidateModelComment] just 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 class a new dialog will pop up with name Add New Item from that 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 now we are going to inherit from ActionFilterAttribute class inside that we are going to 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 now let’s implement OnActionExecuting method of it. In this method we are going check Model which is posted is valid or not if not then we are going to 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 OnActionExecuting method let’s apply it ApiController [ValuesController] post method which we have created earlier.

 

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

 

After adding ActionFilterAttribute now we are going get error Message in response when field is empty now we need to handle that in jquery Ajax Post Method when we post data and textbox is empty then it will return and Reponses with 404 status code.

Handling error in Jquery Ajax Post Method

The code which is in red mark is newly added. If any user submit blank comment then the request goes to ValuesController Post Method [POST api/values] before  method executed the ActionFilter on that method gets executed as ActionFilter and check model is valid or not if not then it creates 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 browser from server along with statusCode. In Ajax we have parameter called statusCode which we are going to use to handle error when we sent 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 are going to iterate object and append to Error to Div tag for 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 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 now 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 Add comment button when user submit blank comment then the request goes to ValuesController Post Method [POST api/values] before 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 which we get when field of 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 error response we iterate error which we get and append error to div tag.

 

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

 

Finally we are displaying 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.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User