Today I would like to introduce how to use dynamic layout with ASP.NET MVC3. The purpose of this article is end user can chose and change layout of website to view data.
1. Create a new project: open VS -> New -> Project
On the next screen, you have the options around the type / template of MVC 3 Project to create. For our purposes select the Empty Application and the Razor view engine. Click OK and your project will create.
2. Right click on the Shared folder (that is under the Views folder), select Add –> New Item. Select the MVC 3 Layout Page (Razor) and enter _Layout1.cshtml as the Name.
3. Add some render sections and a <h1> tag to show that this is layout 1
4. Next we need to add a controller. So go to Controllers in Solution Explorer, right click and select Add –> Controller, and call it HomeController. Do not select the check box to add action methods for create, update, delete and details scenarios.
5. And finally, we need to create the view to show with the correct layout. In the home controller, right click anywhere in the Index function and select Add View. Make sure you check the Use a layout or master page and have selected the _Layout1.cshtml layout that we have created.
Now, lets add the content to the view so that something is displayed. That is in the code below.
Now, if you press F5 you should get the following webpage.
6. So, first lets create our second page layout. Right click on the Shared folder in the View folder, then add a new item. As before, MVC 3 Layout Page (Razor) but this time enter _Layout2.cshtml as the Name. Below is the code for _Layout2.cshtml
7. Now, we need to update the controller. That is in the code below.
8. And then need to changes to the view. One to alter the layout (from the viewbag rather than hardcoded, and the other to create a link to control the querystring. The new view code is below:
9. Press F5. If you click on the link you should alternate between the two layout: