如何使用c#MVC4在$ .ajax中调用错误函数?

Fla*_*nix 1 javascript c# ajax jquery asp.net-mvc-4

我在MVC4中有一个C#项目.在这个项目中,我的一个控制器有一个方法可以被Ajax函数调用:

[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;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用jQuery通过以下Ajax函数调用此方法:

$.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);
    }
});
Run Code Online (Sandbox Code Playgroud)

这段代码的问题在于,即使服务器"An error occurred, please try later! " + exc.Message;在catch中返回返回消息,成功函数也是总是被调用的函数.

换句话说,无论我做什么,我都不会运行错误功能.

为了解决这个问题,我检查了官方文档:

但是,由于我对此不熟悉,我无法理解任何参数,也无法理解如何有效地使用它们.

如何使用Ajax,jQuery和我的控制器创建包含所有可能信息的良好错误消息?

Ror*_*san 6

error该部分$.ajax只调用如果返回的状态代码比其他任何火灾200 OK.在您的情况下,您将返回明文响应,因此将是200.您可以像这样更改此行为:

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

您可以将其更改HttpStatusCode为适合您需要的任何内容.

或者,您可以保留200响应并返回带有标志的JSON,以指示请求是否成功:

[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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以删除error处理程序,并检查处理程序中的标志状态success:

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