开发者

Redirecting to error page if a partial view encounters an error [duplicate]

开发者 https://www.devze.com 2023-03-09 17:18 出处:网络
This question already has answers here: ASP.NET MVC Custom Error Handling Application_Error Global.asax?
This question already has answers here: ASP.NET MVC Custom Error Handling Application_Error Global.asax? (10 answers) Closed 2 years ago.

I'm rendering a partial view inside of a view:

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

Is there a way to redirect the user to an error page if the partial view act开发者_如何学JAVAion encounters an error?

EDIT: I'm looking for a server side kind of redirection. This partial view is not loaded with AJAX. It is rendered server side into a "big" view. The "big" view has no idea that the partial view errored out.


Depending on your logic, you might be able to control your application flow by using jQuery.ajax() to handle errors.

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

This will handle an error in the GET, but of course if you were to return some JSON or some other indicator in your action method, you could use the same window.location.href... in the success callback function.

Edit

Also see above edits to $.ajax

Your controller could do something like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消