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

标签 asp.net-mvc-2 handleerror

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

相关文章:

javascript - 如何克服这个安全问题

c# - 使用 Entity Framework 将新记录插入数据库

model-view-controller - 使用 Action 过滤器进行MVC错误处理

asp.net-mvc-2 - MVC for IE 中的 Excel 导出不允许打开多个窗口

c# - 我应该在哪里设置语言(CurrentThread.CurrentCulture)?

jquery - 响应内容类型与预期不同

asp.net-mvc - ASP.NET MVC 处理错误

c# - 本地蓝屏vs远程处理错误

jquery - 如何使用 MVC 从 catch block 重定向到另一个 View