gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:15:18 25 4
gpt4 key购买 nike

我有一个编译错误的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com