Search code examples
http-redirectasp.net-mvc-5asp.net-mvc-viewmodelasp.net-mvc-viewsonexception

MVC 5 - Pass object to a shared view


I am developing a MVC 5 internet application and have a question in regards to passing an object to a shared view.

I have a view called CustomError.cshtml in the shared folder. This view has the following model type: @model CanFindLocation.ViewModels.CustomErrorViewModel

How can I pass an object of type CanFindLocation.ViewModels.CustomErrorViewModel to this view from the protected override void OnException(ExceptionContext filterContext) function in a controller?

Here is my code:

protected override void OnException(ExceptionContext filterContext)
{
    Exception e = filterContext.Exception;

    if (e is HttpRequestValidationException)
    {
        filterContext.ExceptionHandled = false;
        customErrorViewModel = customErrorService.GetDefaultCustomError(customErrorType, "Test message.");
        RedirectToAction("CustomError", customErrorViewModel);
    }
}

Instead of the view being shown, the following function is called:

protected void Application_Error(object sender, EventArgs e)

Thanks in advance.


Solution

  • I don't think you can return view as you want, so I usually put values into TempData and make a redirection to homepage or whatever landing page.

    Homepage check is there is value into this Viewbag and show error if there is error.

    Controller:

    public class BaseController : Controller
        {
            protected void SetError(string message, params object[] args)
            {
                TempData["UIError"] = string.Format(message, args);
            }
        }
    

    In in my shared (master) layout view:

    @if (TempData["UIError"] != null)
            {
                <div class="alert alert-danger" role="alert">
                    <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                    <span class="sr-only">Error:</span>
                    @TempData["UIError"]
                </div>
            }