Returning partial view and error response together

heymega picture heymega · Oct 17, 2013 · Viewed 9.2k times · Source

I have a situation whereby I need to return an exception to the client in the form of a partial view. Here is my code

            catch(PasswordException ex)
            {
                Response.StatusCode = 500;
                ViewBag.Message = ex.Message;
                return PartialView("Exception");
            }

I'm setting the response statuscode to 500 so the response is caught in the error section of the ajax call.

This works fine but it seems a bit overkill to return a server error just to flag this exception.

Is there a better/standard way of doing this?

Answer

Amit picture Amit · Oct 17, 2013

Try this,Create Custom error enum and use as below:

/// <summary>
/// Redirect to custom error page.
/// </summary>
/// <returns>View for custom error page.</returns>
public ActionResult Error(CustomError customErrorType,string message)
{
switch (customErrorType)
    {
        case CustomError.A:
            @ViewBag.ErrorMessage = message;
            @ViewBag.Title= CustomError.A;
            break;
        case CustomError.B:
            @ViewBag.ErrorMessage = message;
            @ViewBag.Title= CustomError.B;
            break;          
    }
    return View("_CustomError");
}

View

@{
    @ViewBag.Title
  }

    @ViewBag.ErrorMessage

Redirect as below:

catch(PasswordException ex)
    {
        Response.StatusCode = 500;
        return RedirectToAction(Response.StatusCode,ex.Message);
    }