ASP.NET MVC 3: Using multiple view engines in same project
One of nice features of ASP.NET MVC 3 is support for multiple view engines. There will be two out-of-box view engines: one for classic ASPX-based views and one for Razor-based views. In this posting I will show you this new feature and demonstrate how to use different view engine in same project.
Currently, I think, there is no real application to tricks in this posting but you never know. When ASP.NET MVC has been available for longer period of time I think there will be need to migrate two projects that use different view engines.
Support for multiple view engines
Here you can see screenshot of Add View dialog where view engine dropdown is opened.
Currently there are two choices:
- ASPX – classic ASP.NET MVC views,
- Razor – new Razor based views.
If you select another view engine then file and master page names are changed appropriately.
In the future there will be maybe third option for Visual Basic.NET based Razor views (CSHTML means C# based views).
Using multiple view engines in same project
Now let’s make little experiment. Here is my step by step guide.
- Create ASP.NET MVC 3 ASPX project.
- Create ASP.NET MVC 3 Razor project.
- Copy Site.master and LogOnUserControl.ascx from ASPX project shared views folder to Razor project shared views folder.
- Copy About.aspx from Home views folder of ASPX project to Home views folder of Razor project.
- Rename About.aspx to AboutAspx.aspx.
- Open _Layout.cshtml and add the following line to the end of menu:
<li>@Html.ActionLink("About ASPX", "AboutAspx", "Home")</li>
- Open Site.master and add the following line to the end of menu:
<li><%: Html.ActionLink("About ASPX", "AboutAspx", "Home")%></li>
- Save both master pages.
- Open AboutAspx.aspx and change the text in body so you can recognize that ASPX-based view is shown.
- Save AboutAspx.aspx.
Now you can run your project and select About and About ASPX from main menu. If you select About you will see Razor-based view and if you select About Aspx you will see ASPX-based view.
Using views based on different view engines allows us to migrate ASP.NET MVC projects that are written using different view engines. As human mind is unlimited I have to suggest that it is not good idea to use different view engines in same project. Try to avoid pointless mess if you can and select view engine by trusting your common sense.