【问题标题】:.net MVC handle view compilation error loaded by ajax.net MVC 处理 ajax 加载的视图编译错误
【发布时间】:2012-08-15 23:00:06
【问题描述】:

我有一个编译错误的视图。此视图通过 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 错误处理程序返回简单的错误消息?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 jquery error-handling


    【解决方案1】:

    您可以在 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) { }
    });
    

    【讨论】:

    • 谢谢!正是我需要的。
    猜你喜欢
    • 2013-05-29
    • 2014-06-16
    • 2015-06-03
    • 2011-06-10
    • 2019-02-11
    • 1970-01-01
    • 2011-04-02
    • 2016-06-22
    • 1970-01-01
    相关资源
    最近更新 更多