我在asp.net mvc Web应用程序中使用Jquery UI选项卡。我的标签运作良好。
但是,问题是,每当发生ajax错误时,都应该捕获该错误,并且应该将JSON响应返回。
我正在通过MVC HandleError属性使用CustomError处理程序,如下所示:
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
{
return;
}
if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
{
return;
}
// if the request is AJAX return JSON else view.
if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
error = true,
message = filterContext.Exception.Message
}
};
}
else
{
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = View,
MasterName = Master,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
}
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
因此,如果发生错误并且它是ajax request,那么上述方法将抛出JSON响应。
但是,我正在努力寻找如何捕获该JSON响应并将其显示在客户端上。
请帮助..我尝试将ajaxoptions与UI选项卡一起使用,如下所示:
$(document).ready(function () {
$('#tabs').tabs({
activate: function (event, ui) {
ui.oldPanel.empty();
},
ajaxOptions: { success: Success, error: Failure }
});
$('#tabs').css('display', 'block');
$(function () {
$(this).ajaxStart(function () {
$("#ajaxLoading").show();
});
$(this).ajaxStop(function () {
$("#ajaxLoading").hide();
});
});
});
function Success(data) {
alert("Successfully loaded the tabs");
}
function Failure() {
alert("Some thing wrong had happened");
}
请提供帮助。.如何接收错误的JSON响应并向最终用户显示适当的警报。
最佳答案
我发现解决方案是这样的:
$.ajaxSetup({
type: "GET",
cache: false,
error: function (e) {
var Error = e.responseText;
var ErrorCode= xx;
alert("Sorry, An Error has been occured while processing your request " + Error);
}
});
我已经使用
ajaxSetup()
从服务器端接收响应。希望这可以帮助...
关于asp.net-mvc - 如何在使用Jquery UI选项卡和Custom Error处理程序时捕获Ajax错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20047585/