如何在Ajax方案中返回错误

Moh*_*lli 21 asp.net ajax asp.net-mvc jquery

我正在使用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("");
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我的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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

Ric*_*ick 32

我会在你的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
}
Run Code Online (Sandbox Code Playgroud)

在控制器的操作中,如果发现错误

Response.StatusCode = (int)HttpStatusCode.BadRequest; 
return Content(errorMessage, MediaTypeNames.Text.Plain);
Run Code Online (Sandbox Code Playgroud)