Monday, June 9, 2014

ASP.NET MVC AJAX error handling through filters and jQuery

Consider a scenario where you make an AJAX request in ASP.NET MVC through jQuery, i.e. $.ajax.  If you want to handle server side validations/exceptions and trap them in "error" callback of $.ajax, you can do it in a slick way:

1) Create a filter attribute:

public class ClientErrorAttribute : System.Web.Mvc.FilterAttribute, System.Web.Mvc.IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            var response = filterContext.RequestContext.HttpContext.Response;
            response.Write(filterContext.Exception.Message);
            response.ContentType = MediaTypeNames.Text.Plain;
            filterContext.ExceptionHandled = true;
        }
    }

2) Apply filter to controller/action

[ClientError]
public class HomeController : Controller
{

}

3) Throw exceptions

[HttpGet]
public JsonResult CheckLogin()
{
 if (!User.IsLoggedIn)
 {
  throw new Exception("You are not authorised to perform this operation");
 }
}

4) Catch exceptions in jQuery

$.ajax({
    type: "post", url: "/SomeController/SomeAction",
    success: function (data, text) {
        //...
    },
    error: function (request, status, error) {
        alert(request.responseText);
    }
});

2 comments:

Pavithra M said...

Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. Dot Net Training in chennai | Dot Net Training in velachery

Mithun Mithun said...

It is really a great work and the way in which u r sharing the knowledge is excellent.
Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.. dot net training in chennai | best dot net training in chennai