MVC ajax call how to handle error responses

ajax, asp.net, asp.net-mvc, asp.net-mvc-5, c#

Solution

You can handle your Ajax calls by creating an object that represents the response:

public class AjaxResponse
{
        public bool Success { get; set; }
        public string Message { get; set; }
    }
}

Then return it as follows:

public ActionResult DeletePicture(int id)
{
    // success failed by default
    var response = new AjaxResponse { Success = false };
    try 
    {
     bool success = Operations.DeleteArticle(id);
     response.Success = success;
     // Set a message for UI
     response.Message = success ? "Success" : "Failed";
     }
     catch
     {
      // handle exception
      // return the response with success false
      return Json(response, JsonRequestBehavior.AllowGet);
     }
     return Json(response, JsonRequestBehavior.AllowGet);
}

You could then pass the data and handle it as follows:

$.ajax({
    url: "/Article/DeleteArticle/",
    type: "GET",
    data : { Id : id },
    dataType: 'json',
    error: function (response) {

    // Handle error from response.Success or response.Message

    },
    success: function (response) {

        // Handle error from response.Success or response.Message

    }
});

The handle error could simply display the message back to an HTML element or popup some kind of javascript notification.

Problem

I have a question regarding the ajax call: here is my ajax call: ``` $.ajax({ url: "/Article/DeleteArticle/"+id, type: "GET", error: function (response) { }, success: function (response) { } }); ``` And here is my controller: ``` public ActionResult DeletePicture(int id) { bool success = Operations.DeleteArticle(id); return null; } ``` I would like to know what shoulud i return to get inside error? And when is this error function is called basically? If error happens on server or ..? And regarding the success how can i pass there some data? Real life example: Imagine i call this ajax method to delete an article, when it is deleted, so success i would like to show some success message. If it failed so in my action i get success=false, i would like to show some other message, like : failed. How to achieve that?

Original source