如何让HandleErrorAttribute与Ajax一起工作?

时间:2010-07-18 08:17:25

标签: asp.net-mvc-2 handleerror

在我的ASP.NET MVC 2应用程序中,我使用HandleErrorAttribute在未处理的异常情况下显示自定义错误页面,除非在Ajax.ActionLink调用的操作中发生异常,否则它将完美运行。在这种情况下没有任何反应是否可以使用HandleErrorAttribute用“Error.ascx”局部视图的内容更新目标元素?

1 个答案:

答案 0 :(得分: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>