怎样才能让阿贾克斯HandleErrorAttribute工作? [英] How can I make HandleErrorAttribute work with Ajax?

查看:103
本文介绍了怎样才能让阿贾克斯HandleErrorAttribute工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET MVC 2应用程序我使用HandleErrorAttribute在未处理的异常的情况下,显示自定义错误页,和它完美的作品,除非例外,由Ajax.ActionLink称为动作发生。在这种情况下,没有任何反应。是否有可能使用HandleErrorAttribute与Error.ascx局部视图的内容更新目标元素?

In my ASP.NET MVC 2 application I use HandleErrorAttribute to display a custom error page in case of unhandled exceptions, and it works perfectly unless the exception happens in an action called by Ajax.ActionLink. In this case nothing happens. Is it possible to use HandleErrorAttribute to update the target element with the contents of an "Error.ascx" partial view?

推荐答案

要做到这一点,你可以写一个自定义操作过滤器:

To achieve this you could write a custom action filter:

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;
        }
    }
}

然后指定局部视图中使用:

And then specify the partial view to be used:

[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");
    }
}

终于在你看来假设你有以下链接:

And finally in your view assuming you have the following link:

<%= Ajax.ActionLink("some text", "someAction", new AjaxOptions { 
    UpdateTargetId = "result", OnFailure = "handleFailure" }) %>

您可以使 handleFailure 函数更新正确的DIV:

You could make the handleFailure function to update the proper 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>

这篇关于怎样才能让阿贾克斯HandleErrorAttribute工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆