如果部分视图遇到错误,则重定向到错误页面

时间:2011-06-01 20:22:44

标签: asp.net-mvc-3 c#-4.0

我在视图中呈现局部视图:

@{
    Html.RenderAction("PartialViewAction", "SomeController");
}  

如果部分视图操作遇到错误,是否有办法将用户重定向到错误页面?

编辑:我正在寻找服务器端的重定向。此部分视图未加载AJAX。它将服务器端呈现为“大”视图。 “大”视图不知道部分视图出错了。

2 个答案:

答案 0 :(得分:1)

也许我误解了这个问题,但是如果渲染调用抛出异常,你不能只在global.asax中使用Application_Error方法吗?请参阅here

答案 1 :(得分:0)

根据您的逻辑,您可以使用jQuery.ajax()来处理错误,从而控制应用程序流程。

// this will render the GET request on page load
$(function() {
    $.ajax({
        url: '/Some/PartialViewAction',
        type: 'GET',
        dataType: 'json',                            /*edit*/
        success: function(xhr_data) {                /*edit*/
            // the following assumes you wrap 
            // your partial view in div id="myDiv"
            $('#myDiv').html(xhr_data.html);         /*edit*/
            $('#myErrorDiv').html(xhr_data.error);   /*edit*/
        },
        error: function() {
            window.location.href='/Some/Error';
            // or similar page redirecting technique
        }
    });
});

这将处理GET中的错误,但当然如果您在操作方法中返回一些JSON或其他指示符,则可以在window.location.href...回调函数中使用相同的success

修改

另见$.ajax

的上述编辑

您的控制器可以执行以下操作:

public ActionResult PartialViewAction() {
    // handle error
    string message = "Evacuate, Immediately!";
    // not certain the html will render correctly,
    // but you could encode/parse/whatever easily enough
    return Json(new { html = "<div>some html</div>", error = message },
        JsonRequestBehavior.AllowGet);
}