tags:

views:

60

answers:

2

What is the correct way to dynamically change the View (the view aspx) that a controller method uses versus using the standard naming convention.

I'm guessing it has something to do with the ViewResult and ViewName, but what is the correct syntax?

Update:
One thing I forgot... is there a way to do this without having the "action" or method name not be part of the resulting URL?

For example,
If I wanted to have a list of all the states in the USA.
http://localhost/list/states
(displays a simple list of state names)

And If I wanted to have a list of the 50 largest cities in the USA.
http://localhost/list/largest-cities
(displays the city and the population - two column grid)

So I'd like to be able to pull in different "formatters" depending on the list name.

Should I do that in a single action / multiple views?
Could I then use Routes to hide the View name in the URL?
What is the best way to approach this?

A: 

If you need to render a different view from a controller action dynamically, you can simply supply a value to the base.View() method (or the ViewResult constructor). The location of the view will always be (for the web forms view engine):

/Views/{Controller}/{View}.aspx

Edit: (Thanks to Ithi) It could also be in:

/Views/Shared/{View}.aspx
Richard Szalay
Technically it could come from the shared folder too. (Aside: In past projects I've written my own viewengine because I was dissatisfied with the "forced folder" behavior.)
Joel Potter
Does it search in Shared first? or under the Controller name first?
tyndall
Controller name, then Shared
Richard Szalay
+1  A: 

Just use the method that takes the name of the view to choose. Be careful, though. Most times what you probably want to do is redirect to a different action instead. Returning a different view won't change the url like redirecting will.

string name = ...figure out which view you want...

return View( name );
tvanfosson
So what are you saying is I can do a lot of redirecting through the Index without changing the URL? That is what I want in this circumstance.
tyndall
This might be what you want, but typically I'll only return a different view if there is an error, which returns a shared error view, or a validation issue, which returns the view from which the action was invoked. I prefer to keep my URLs RESTful and not have the view be context dependent.
tvanfosson
+1 and Answer. Good food for thought. I'll look at keeping one view and somehow plugging in a "formatter" for the Grid/Table that I'll be using on every page.
tyndall
You might want to consider a ViewUserControl and rendering via RenderPartial in each view that should contain the Grid/Table. Move the code to generate the data off to your BL where it can be invoked by any action that needs to supply data for the control.
tvanfosson