Global Error handling using PartialView in MVC
Asked Answered
T

0

0

I have look at one of the perfect article on Exception handling in ASP.NET MVC and want to implement a method as on Method 6 in this article in order to reuse the same error page for all of other modal dialogs on error and exception situations. On the other hand, as I use popup window, I need to render a PartialView in my modal dialog instead of redirecting the page. Is it possible to do this?

AJAX call:

$.ajax({
    type: "POST",
    url: '@Url.Action("Delete", "Person")',
    cache: false,
    dataType: "json",
    data: formdata,

    success: function (response, textStatus, XMLHttpRequest) {
        if (response.success) {
            //display operation result
        }
        else {
            /* At this stage I need to render the Error view as partial without 
            redirecting to Error page on error. The problem at here not directly 
            related to rendering partialview. I need to render the global Error 
            page and reuse it for every error occured on my modal dialog */
            @Html.Partial("~/Views/Home/Error.cshtml", Model)
        }
    }
});

Controller:

[HttpPost]
public JsonResult Delete(int id)
{
    try
    {
        //code omitted for brevity
    }
    catch (Exception  ex)
    {
        return Json(new { success = false, message = "Operation failed." });
    }
}
Talithatalk answered 20/9, 2016 at 12:41 Comment(5)
You cannot use @Html.Partial() - that is server side code and is evaluated before its sent to the browser. One option would be to return the partial as JSON - refer this answer for an example. Another option would be make a 2nd ajax call in the else block to a method that returns your partialUnderstate
@StephenMuecke Do you meant to change the Redirect section as return Json(new { error = true, message = RenderViewToString(PartialView("Error", model))}); in order to render the error page? But I am not sure how to change the Home/Error page in this article given in the question. For example what if I want to create the error page as _Error in Shared folder?Talithatalk
No, your making an ajax call and ajax calls cannot redirect.Understate
Sorry, but I have no experience with error handling except from basic try-catch methods. So, could you please have a look at the article and then post the modified Controller method that I should use? Thanks.Talithatalk
@StephenMuecke Any idea please?Talithatalk

© 2022 - 2024 — McMap. All rights reserved.