ASP.NET MVC Training in Mumbai Andheri (12th and 13th Saturday and Sunday)

As usual this ASP.NET MVC Mumbai training batch experience was awesome. We had people coming from Kolhapur which just makes us confident that we are doing good work.

But as a trainer we also learn lot of things and grow with every training and project.One of participants asked how to handle errors from ASP.NET MVCWebAPI to Angular gracefully. For example see the below ASP.NET MVC WebAPI code with the “post” method. In the below post method we are getting a customer object and this customer object is checked for business validations.

Now if the validations are fine we would like to return “Customer” object and if there are errors we would like to return validation errors. This is where “HttpResponseMessage” class comes to rescue. This class has two sections one is the data and the other is the status code. So if everything is fine we are returning the OK Http code with customer object or else we are returning bad request with errors.

You can also check for other HTTP status code as per your needs.

public class CustomerWebController : ApiController
{
public HttpResponseMessage Post(Customer obj) 
{
// Customer object validated here ( code removed for clarity)
if(isValid)
{
return Request.CreateResponse(HttpStatusCode.OK, custs);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
}
}

Now in Angular where you are making “HTTP” callyou need to implement “success” and “failure” functions. The HTTP OK response from webAPI is sent to the Angular “success” function and the HTTP bad request is sent to “error” function.

$http({method: "POST",data: $scope.Customer, url: "/Api/CustomerWeb"})
.success(function (data) 
{
// Success code goes here
}).error(function (err)
{
// Error binding goes here
});

Thanks friends for visiting us at Step by Step and wish the best for your future. Our Next ASP.NET MVC Mumbai training batch is on 19th and 20th December i.e. coming week. You can see the syllabus from http://stepbystepschools.net/?page_id=315

MVC

Comments

comments

This entry was posted in Class Room Training, MVC and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.