简体   繁体   中英

MVC ajax call how to handle error responses

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?

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.

you can use it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM