如何在Ajax方案中返回错误

我正在使用ASP.NET MVC和jQuery。 我有以下MVC Action,它返回Success上的部分页面。 在应用程序错误,我不知道发送什么来正确处理它在客户端:

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(""); } } 

以下是我的jQuery ajax调用。 请注意,我正在检查数据长度以确保没有错误。 请建议我这样做的更好方法。

 $.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); } } }); 

我会在你的ajax调用设置中添加一个错误函数。 让服务器确定要显示的错误消息,并将其传递给ajaxerror handling程序并让它显示它。

 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); 

我想你可以做return Content(false.ToString().ToLower()); 如果抛出错误,然后检查数据是否为false

 if(data != false) { //do stuff } 

要么

 if(!data) alert("Error"); else { //do stuff }