gpt4 book ai didi

asp.net-mvc-2 - 如何使 HandleErrorAttribute 与 Ajax 一起使用?

转载 作者:行者123 更新时间:2023-12-03 02:33:31 25 4
gpt4 key购买 nike

在我的 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/

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