Asp.net mvc 2 如何使HandleErrorAttribute与Ajax一起工作?
在我的ASP.NET MVC 2应用程序中,我使用HandleErrorAttribute在出现未经处理的异常时显示一个自定义错误页面,除非异常发生在由Ajax.ActionLink调用的操作中,否则它工作正常。在这种情况下,什么也不会发生。是否可以使用HandleErrorAttribute使用“Error.ascx”局部视图的内容更新目标元素?要实现此目的,您可以编写自定义操作筛选器:Asp.net mvc 2 如何使HandleErrorAttribute与Ajax一起工作?,asp.net-mvc-2,handleerror,Asp.net Mvc 2,Handleerror,在我的ASP.NET MVC 2应用程序中,我使用HandleErrorAttribute在出现未经处理的异常时显示一个自定义错误页面,除非异常发生在由Ajax.ActionLink调用的操作中,否则它工作正常。在这种情况下,什么也不会发生。是否可以使用HandleErrorAttribute使用“Error.ascx”局部视图的内容更新目标元素?要实现此目的,您可以编写自定义操作筛选器: public class AjaxAwareHandleErrorAttribute : HandleEr
public class AjaxAwareHandleErrorAttribute : HandleErrorAttribute
{
public string PartialViewName { get; set; }
public override void OnException(ExceptionContext filterContext)
{
// Execute the normal exception handling routine
base.OnException(filterContext);
// Verify if AJAX request
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// Use partial view in case of AJAX request
var result = new PartialViewResult();
result.ViewName = PartialViewName;
filterContext.Result = result;
}
}
}
然后指定要使用的局部视图:
[AjaxAwareHandleError(PartialViewName = "~/views/shared/error.ascx")]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult SomeAction()
{
throw new Exception("shouldn't have called me");
}
}
最后,在您看来,假设您有以下链接:
<%= Ajax.ActionLink("some text", "someAction", new AjaxOptions {
UpdateTargetId = "result", OnFailure = "handleFailure" }) %>
本页也值得一读,因为它为此事添加了更多信息:
<script type="text/javascript">
function handleFailure(xhr) {
// get the error text returned by the partial
var error = xhr.get_response().get_responseData();
// place the error text somewhere in the DOM
document.getElementById('error').innerHTML = error;
}
</script>