user3428422
user3428422

Reputation: 4560

How can I redirect to a view without a controller in an ASP.NET MVC application?

I have created a generic error view that I want to show when a exception occurs inside action methods across the site. I have created a partial page where all the navigation lives so therefore I do not need a controller on this view, so how do I redirect to it from an action method inside a controller?

Something like this...

 [HttpPost]
 public ActionResult Test(VM viewModel)
 { 
     try
     {
         // posting info to the server...
     }
     catch (Exception ex)
     {
        //Log exception..

        //show an error view, however no action method so how do I redirect?
        return RedirectTo ??? ("Error");
     }
  }

Upvotes: 1

Views: 9520

Answers (2)

Jim Skerritt
Jim Skerritt

Reputation: 4596

You will need to create a controller and a route for your error view.

An alternative approach is to make your error view a plain HTML page and just redirect to it like this:

return Redirect("~/error.html");

I found this guide to be very useful when setting up custom errors on other MVC applications: http://benfoster.io/blog/aspnet-mvc-custom-error-pages

Upvotes: 4

Tushar Gupta
Tushar Gupta

Reputation: 15923

You can use return View() in your method:

{
    //Log an exception...   
    //show an error view, however no action method so how do I redirect?
    return View("your view path");
}

This tells your MVC application to generate HTML to be displayed for the specified View and sends it to the browser. This acts like as Server.Transfer() does in ASP.Net Web Forms.

Upvotes: 5

Related Questions