在我的 ASP.NET MVC 2 应用程序中,我使用 HandleErrorAttribute 在出现未处理异常的情况下显示自定义错误页面,并且除非异常发生在 Ajax.ActionLink 调用的操作中,否则它会正常工作。在这种情况下什么也不会发生。是否可以使用 HandleErrorAttribute 用“Error.ascx”部分 View 的内容更新目标元素?
最佳答案
要实现此目的,您可以编写自定义操作过滤器:
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;
}
}
}
然后指定要使用的局部 View :
[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" }) %>
您可以使用handleFailure
函数来更新正确的div:
<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>
关于asp.net-mvc-2 - 如何使 HandleErrorAttribute 与 Ajax 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3274808/