MVC ajax call how to handle error responses

I have a question about 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 will return to get inside the error? And when is this error function called mainly? If the error occurs on the server or ..?

And regarding success, how can I transfer some data there?

Real life example:

Imagine that I call this ajax method to delete an article when it is deleted, so success I would like to show a success message. If this failed in my action, I get success = false, I would like to show another message, for example: failed.

How to do it?

+4
source share
2

Ajax, , :

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

:

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);
}

:

$.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

    }
});

HTML - javascript.

+4

public ActionResult DeleteArticle(int id)
{
    bool success = Operations.DeleteArticle(id);       

    return Json(success, JsonRequestBehavior.AllowGet);
}


$.ajax({
    url: "/Article/DeleteArticle/",
    type: "GET",
    data : { Id : id },
    dataType: 'json',
    error: function (response) {    
       if(response!=null && response.length!=0)
       {
         alert('error');
       }    
    },
    success: function (response) {  
       if(response) {
         alert('Success');
       }   
    }
});
+1

Source: https://habr.com/ru/post/1524708/


All Articles