我在 Controller 中有一个如下所示的方法:
[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 中,我有以下 block 来调用此方法:
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',
url: '/Account/UnfavoriteEvent',
data: { id: $("#EventID").val() },
success: function(data, textStatus, jqXHR) {
// jqXHR.status contains the Response.Status set on the server
},
error: function(jqXHR, textStatus, errorThrown) {
// jqXHR.status contains the Response.Status set on the server
}});
如您所见,您必须将 error
函数传递给 ajax
函数...在您的示例中,您将函数设置为
属性完全无效。jqXHR
的错误
关于 ajax 事件的文档
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",
new { EventID = id, 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);
}
}
关于c# - 从 MVC HttpPost 将错误返回给 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12966395/