c# – 从MVC HttpPost向jQuery返回错误

前端之家收集整理的这篇文章主要介绍了c# – 从MVC HttpPost向jQuery返回错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在控制器中有一个方法,如下所示:

[HttpPost]
public void UnfavoriteEvent(int id)
{
    try
    {
        var rows = _connection.Execute("DELETE UserEvent WHERE UserID = (SELECT up.UserID FROM UserProfile up WHERE up.UserName = @UserName) AND EventID = @EventID",new { EventID = id,UserName = User.Identity.Name });
        if (rows != 1)
        {
            Response.StatusCode = 500;
            Response.Status = "There was an unknown error updating the database.";
            //throw new HttpException(500,"There was an unknown error updating the database.");
        }
    }
    catch (Exception ex)
    {
        Response.StatusCode = 500;
        Response.Status = ex.Message;
        //throw new HttpException(500,ex.Message);
    }
}

正如你所看到的,我尝试了几种不同的方法来抛出这个错误.在JavaScript中,我有以下块来调用方法

var jqXHR;
if (isFavorite) {
    jqXHR = $.ajax({
        type: 'POST',url: '/Account/UnfavoriteEvent',data: { id: $("#EventID").val() }
    });
}
else {
    jqXHR = $.ajax({
        type: 'POST',url: '/Account/FavoriteEvent',data: { id: $("#EventID").val() }
    });
}

jqXHR.error = function (data) {
    $("#ajaxErrorMessage").val(data);
    $("#ajaxError").toggle(2000);
};

现在,我想要做的是将抛出的错误抛回jqXHR.error函数,以便我可以正确处理它.

目前,取消注释的代码抛出一个异常,说我不允许放置在Status中的文本,并且注释代码实际上返回标准错误页面作为响应(实际上并不奇怪).

所以,我有几个问题:

>如何正确抛出错误
> Response.Status属性有什么作用?

谢谢大家!

最佳答案
您将能够从javascript端获取响应状态,执行以下操作:

$.ajax({
    type: 'POST',data: { id: $("#EventID").val() },success: function(data,textStatus,jqXHR) {
        // jqXHR.status contains the Response.Status set on the server
    },error: function(jqXHR,errorThrown) {
        // jqXHR.status contains the Response.Status set on the server
    }});

如您所见,您必须将错误函数传递给ajax函数…在您的示例中,您将函数设置为jqXHR的error属性,完全没有任何影响.

有关ajax事件的文档

> jQuery – Ajax Events

jQuery文档说错误字符串将出现在errorThrown参数中.

不要使用Response

相反,你应该返回HttpStatusCodeResult:

[HttpPost]
public void UnfavoriteEvent(int id)
{
    try
    {
        var rows = _connection.Execute("DELETE UserEvent WHERE UserID = (SELECT up.UserID FROM UserProfile up WHERE up.UserName = @UserName) AND EventID = @EventID",UserName = User.Identity.Name });
        if (rows != 1)
        {
            return new HttpStatusCodeResult(500,"There was an unknown error updating the database.");
        }
    }
    catch (Exception ex)
    {
        return new HttpStatusCodeResult(500,ex.Message);
    }
}

猜你在找的jQuery相关文章