5

在我的 ASP.NET MVC 2 应用程序中,我使用 HandleErrorAttribute 来显示自定义错误页面,以防出现未处理的异常,除非异常发生在 Ajax.ActionLink 调用的操作中,否则它可以正常工作。在这种情况下,什么都不会发生。是否可以使用 HandleErrorAttribute 用“Error.ascx”部分视图的内容更新目标元素?

4

1 回答 1

11

为此,您可以编写一个自定义操作过滤器:

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" }) %>

您可以使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>
于 2010-07-18T08:54:53.973 回答