Re-Use MVC Views Across Projects With Razor Generator

Page content

A typical MVC site would consist of a folder containing all the views and partials that are then rendered using a view engine. However, it can get a little tricky when you want to re-use the same view template across multiple projects without content duplication. Perhaps you want to re-use a small partial with tracking code or even entire views for common actions such as login / reporting.

You may consider storing the content in a resource file and embed it in a class library. Or perhaps do a clever virtual directory mapping in your IIS setup. However, the best solution is simply to compile the views into a class library using Razor Generator. Razor Generator is tool that allows processing Razor files at design time instead of runtime, allowing them to be built into an assembly.

Install Razor Generator Extension

In order to get your views compiled, you will need to install a tiny extension. The latest version can be found in the Visual Studio Extensions Gallery. Once installed, you will need to re-start Visual Studio.

The extension will enable RazorGenerator Custom Tool. Custom tools in Visual Studio can be attached to various files to generate automatic classes. For example, the ResXFileCodeGenerator tool looks after auto-generating classes for resource files. Visual Studio comes with several tools built in, however, you can also build your own.

Create Your Shared Project

Add Re-Usable Views

Once you have your common project setup, you can create the same directory structure as you would in a normal MVC project. For example, if you wanted your re-usable partial view to be in shared, you would place it in ~/Views/Shared/YourPartial.cshtml or even ~/Views/Shared/DisplayTemplates/YourPartial.cshtml.

Include a Reference to Your Shared Project

Finally, you should reference the class library into your projects. All you need is a reference to the dll produced when the class library is built. You can then call up any views as if they were present in the solution. The example below assumes you have SharedPartial.cshtml in your ~/View/Shared/ folder in the Example.Common.

1... your view content
2<div class="container">
3    @Html.Partial("SharedPartial")
4</div>
5... your view content

Have fun! If you have any questions, give me a shout @mirajavora.

Razor Generator Extension for Visual Studio Razor Generator Project On Codeplex