加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-2 – 如何让HandleErrorAttribute与Ajax一起工作?

发布时间:2020-12-16 03:36:38 所属栏目:asp.Net 来源:网络整理
导读:在我的ASP.NET MVC 2应用程序中,我使用HandleErrorAttribute在未处理的异常情况下显示自定义错误页面,除非在Ajax.ActionLink调用的操作中发生异常,否则它将完美运行.在这种情况下没有任何反应是否可以使用HandleErrorAttribute用“Error.ascx”局部视图的内
在我的ASP.NET MVC 2应用程序中,我使用HandleErrorAttribute在未处理的异常情况下显示自定义错误页面,除非在Ajax.ActionLink调用的操作中发生异常,否则它将完美运行.在这种情况下没有任何反应是否可以使用HandleErrorAttribute用“Error.ascx”局部视图的内容更新目标元素?

解决方法

要实现此目的,您可以编写自定义操作过滤器:

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读