asp.net-mvc - .net MVC处理由ajax加载的 View 编译错误

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

我有一个编译错误的 View 。该 View 通过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 
    ....
});

发生 View 编译错误时,如何将简单错误消息返回给ajax错误处理程序?

最佳答案

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

关于asp.net-mvc - .net MVC处理由ajax加载的 View 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12040627/

相关文章:

c# - 'System.Data.Entity.Migrations.DbMigrationsConfiguration` 1' 的类型初始值设定项抛出异常

javascript - Razor Dropdown onchange 事件未触发始终未定义

c# - 与 OutputCacheAttribute 交互

c# - 在asp.net mvc3图表助手中如何向系列数据添加标记

c# - 空 json 列表被视为 null

asp.net-mvc - 在浏览器插件中打开pdf

asp.net-mvc - 处理ajax调用中的 session 超时

javascript - 元素出现但不是子元素的选择器

javascript - 为什么在运行图形之前会弹出alert(),但不会弹出对话框或DIV?

javascript - 仅为智能手机加载不同的javascript