0

我有一个编译错误的视图。此视图通过 ajax 调用加载。我想将编译错误消息作为简单的字符串消息返回,但 MVC 将整个 HTML 页面作为错误返回。

我有一个 ajax 错误处理程序,它在 中查找错误消息request.responseText,如下所示:

$(document).ajaxError(function (event, request, settings) {
    ....
    //contains html error page, but I need a simple error message
    request.responseText 
    ....
});

当出现视图编译错误时,如何向 ajax 错误处理程序返回简单的错误消息?

4

1 回答 1

2

您可以在 Global.asax 中编写一个全局异常处理程序,它将拦截 AJAX 请求期间发生的错误并将它们序列化为响应的 JSON 对象,以便您的客户端错误回调可以提取必要的信息:

protected void Application_Error(object sender, EventArgs e)
{
    if (new HttpRequestWrapper(Request).IsAjaxRequest())
    {
        var exception = Server.GetLastError();
        Response.Clear();
        Server.ClearError();
        Response.ContentType = "application/json";
        var json = new JavaScriptSerializer().Serialize(new
        {
            // TODO: include the information about the error that
            // you are interested in => you could also test for 
            // different types of exceptions in order to retrieve some info
            message = exception.Message
        });
        Response.StatusCode = 500;
        Response.Write(json);
    }
}

接着:

$(document).ajaxError(function (event, request, settings) {
    try {
        var obj = $.parseJSON(request.responseText);
        alert(obj.message);
    } catch(e) { }
});
于 2012-08-20T15:51:29.137 回答