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.ContentType = MediaTypeNames.Text.Plain;
            filterContext.ExceptionHandled = true;

2) Apply filter to controller/action

public class HomeController : Controller


3) Throw exceptions

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

4) Catch exceptions in jQuery

    type: "post", url: "/SomeController/SomeAction",
    success: function (data, text) {
    error: function (request, status, error) {