Gavin
Gavin

Reputation: 17392

ASP.Net MVC Redirect To A Different View

Is it possible to redirect to a different view from a controller?

For example, all my controllers inherit from a custom controller that has a constructor that I want to redirect to different view if certain criteria is not met. Hope that makes sense.

Upvotes: 98

Views: 272552

Answers (6)

Scott Tomassetti
Scott Tomassetti

Reputation: 11

return RedirectToAction("index");

This is how I use it in the controller and actionresult that needs to be redirected.

Upvotes: 1

Maeda
Maeda

Reputation: 1305

The simplest way is use return View.

return View("ViewName");

Remember, the physical name of the "ViewName" should be something like ViewName.cshtml in your project, if your are using MVC C# / .NET.

Upvotes: 8

John Sheehan
John Sheehan

Reputation: 78152

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is:

return RedirectToAction("Index", model);

Then in your Index method, return the view you want.

Upvotes: 155

Andrew
Andrew

Reputation: 191

Here's what you can do:

return View("another view name", anotherviewmodel);

Upvotes: 4

Mahender Reddy
Mahender Reddy

Reputation: 237

 if (true)
 {
   return View();
 }
 else
 {
   return View("another view name");
 }

Upvotes: 22

jeffreypriebe
jeffreypriebe

Reputation: 2287

I am not 100% sure what the conditions are for this, but for me the above didn't work directly, thought it got close. I think it was because I needed "id" for my view by in the model it was called "ObjectID".

I had a model with a variety of pieces of information. I just needed the id.

Before the above I created a new System.Web.Routing.RouteValueDictionary object and added the needed id.

(System.Web.Routing.)RouteValueDictionary RouteInfo = new RouteValueDictionary();
RouteInfo.Add("id", ObjectID);
return RedirectToAction("details", RouteInfo);

(Note: the MVC project in question I didn't create, so I don't know where all the right "fiddly" bits are.)

Upvotes: 4

Related Questions