How to call error function in $.ajax with c# MVC4?

Flame_Phoenix

I have a project in MVC4 with C#. In this project, one of my controllers has a method to be called by an Ajax function:

[HttpPost]
public string EditPackage(int id, string newPkgName)
{
    try{
        //do logic here
        return "OK";
    }catch(Exception exc){
        return "An error occurred, please try later! " + exc.Message;
    }
}

This method is called by the following Ajax functions, using jQuery:

$.ajax({
    url: $(this).data('url'),
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    traditional: true,
    data: JSON.stringify({ id: id, newPkgName: newPkgName}),
    success: function () {
        location.reload(true);
        successNotification("Package edited successfuly!");
    },
    error: function (message) {
        errorNotification(message);
    }
});

The problem with this code, is that even if the server returns the return "An error occurred, please try later! " + exc.Message; message in the catch, the success function is the one always called.

In order words, I never run the error function no matter what I do.

To fix this I checked the official documentation:

However, since I am failry new to this I can't understand any of the parameters, nor how to use them effectively.

How can I create a good error message with all the possible information using Ajax, jQuery and my controller?

Rory McCrossan

The error part of the $.ajax call only fires if the returned status code is anything other than 200 OK. In your case you are returning a plaintext response which will therefore be 200. You can change this behaviour like this:

try {
    // do logic here
    return "OK";
}
catch (Exception exc) {
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}
error: function (jqXHR, textStatus, errorThrown) {
    errorNotification(textStatus);
}

You can change the HttpStatusCode to whatever suits your need.

Alternatively, you can keep the 200 response and return JSON with a flag to indicate whether or not the request was successful:

[HttpPost]
public ActionResult EditPackage(int id, string newPkgName)
{
    try {
        //do logic here
        return Json(new { Success = true, Message = "OK"});
    }
    catch (Exception exc) {
        return Json(new { Success = false, Message = "An error occurred, please try later! " + exc.Message });
    }
}

Then you can remove the error handler, and check the state of the flag in your success handler:

success: function(response) {
    if (response.Success) {
        location.reload(true);
        successNotification("Package edited successfuly!");
    }
    else {
        errorNotification(response.Message); 
    }
},

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

MVC4 render image with Ajax call

From Dev

MVC4 cshtml page function call

From Dev

How to receive data sent using ajax call by Post method in MVC4?

From Dev

How to pass a complex view model into a controller action via ajax call with JSON in .Net MVC4?

From Dev

MVC ajax call how to handle error responses

From Dev

How to get json from MVC4 C# with no javascript and no Ajax

From Dev

Json not parsing correctly from jQuery AJAX call in MVC4

From Dev

MVC4 @Html.Checkboxfor issue with Ajax call

From Dev

Call an Action method using Ajax in MVC4

From Dev

mvc4 Razor Ajax Call to show partial view

From Dev

MVC4 ajax call and return data properly

From Dev

Jquery passing data to ajax function in mvc4

From Dev

How to call an ajax function in a for loop

From Dev

ajax error results in success function call

From Dev

MVC4 - How to call controller method from razor view

From Dev

How to enable ajax in asp.net MVC4

From Dev

C call function type error

From Dev

mvc4 how to make a function in controller with null able parameter

From Dev

How to show 'in progress' while a FileResult function is running in MVC4

From Dev

Ajax call to c# function not working

From Dev

c++ : "no matching function for call to" error with function

From Dev

How to call PHP function using jQuery ajax?

From Dev

How to Execute the function after Ajax call is complete

From Dev

How to call a php function from ajax?

From Dev

how to call AJAX function in anchor tag

From Dev

How to call an AJAX function on anchor tag?

From Dev

how to call autocomplete inside ajax function

From Dev

How to call a function when using ajax promise

From Dev

How to call medoo 1.5 inside a function with ajax?

Related Related

HotTag

Archive