Jquery 如何在Ajax场景中返回错误
我正在使用ASP.NETMVC和jQuery。我有以下MVC操作,它返回成功的部分页面。关于应用程序错误,我不确定要发送什么才能在客户端正确处理它:Jquery 如何在Ajax场景中返回错误,jquery,asp.net,ajax,asp.net-mvc,Jquery,Asp.net,Ajax,Asp.net Mvc,我正在使用ASP.NETMVC和jQuery。我有以下MVC操作,它返回成功的部分页面。关于应用程序错误,我不确定要发送什么才能在客户端正确处理它: public ActionResult LoadFilterSet(int filterSetId) { try { BreadCrumbManager bcManager = this.ResetBreadCrumbManager(this.BreadCrumbManagerID); General
public ActionResult LoadFilterSet(int filterSetId)
{
try
{
BreadCrumbManager bcManager = this.ResetBreadCrumbManager(this.BreadCrumbManagerID);
GeneralHelper.LoadBreadCrumbManager(bcManager, filterSetId);
ViewData["BreadCrumbManager"] = bcManager;
return View("LoadFilterSet");
}
catch (Exception ex)
{
return Content("");
}
}
下面是我的jQueryAjax调用。请注意,我正在检查数据长度以确保没有错误。请给我一个更好的方法
$.ajax({
type: "GET",
dataType: "html",
async: true,
data: ({ filterSetId: selectedId }),
url: link,
contentType: "text/html; charset=utf-8",
success: function(data, textStatus) {
if (data.length > 0) {
// Clear the local filters first.
clearLocalFilters();
$('td.selected-filters table.filters-display').append(data);
}
}
});
我认为您可以执行
返回内容(false.ToString().ToLower())代码>如果抛出错误,然后检查数据是否为false
if(data != false)
{
//do stuff
}
或
我将在ajax调用的设置中添加一个错误函数。让服务器确定要显示的错误消息,并将其传递给ajax错误处理程序,然后让它显示
success: function(data, textStatus) {
// Clear the local filters first.
clearLocalFilters();
$('td.selected-filters table.filters-display').append(data);
},
error: function (data) {
alert(data.responseText); // use any display logic here
}
在控制器的操作中,如果发现错误
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Content(errorMessage, MediaTypeNames.Text.Plain);
嗨,Knepe,这或多或少是我在成功函数中所做的。这只允许出现一种故障情况。如果我想给出失败的适当原因,我将无法使用这种方法以优雅的方式完成。触发ajax错误就可以了。我喜欢这个答案。内容的类型是什么?我在文件里没看到。我所看到的是ContentResponse
它不接受状态码,httpstatuscodesult
它将错误包装在html页面中,而System.Web.UI.WebControls.Content
则完全不同
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Content(errorMessage, MediaTypeNames.Text.Plain);