OdeToCode IC Logo

Notes on Building Razor Views

Wednesday, February 16, 2011

Just like web form views, razor views don’t “build” when you build an MVC project in Visual Studio. By default, the parsing and compilation of a view doesn’t happen until runtime, meaning you might not know about a syntax error in a view until you hit the application with a web browser.

Since it’s first release, ASP.NET MVC has provided the ability to parse and compile views at build time by manipulating the underlying MSBuild (.csproj) file. The option works for both web forms (.aspx) and Razor (.cshtml) views.

1. Right-click the MVC project and select “Unload”

2. Right-click the unloaded project and select “Edit”

3. Locate the <MvcBuildViews> element and set its value to “true”.

4. Save the file, then right-click the unloaded project and reload.

With MvcBuildViews set to true, you’ll find out about any syntax problems when you compile a project. Also, Al Gonzalez has a Visual Studio macro to turn the above steps into a one-click operation.

Building views will significantly increase your overall build time, so you might consider only setting the option to true for release builds. 

<PropertyGroup 
  Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
  <MvcBuildViews>true</MvcBuildViews>

</PropertyGroup>

What’s Up With .Edmx Files?

If you happen to have an Entity Framework edmx file directly inside your MVC project, you might see the following error when you eagerly build views.

Could not load type 'System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider'.

This error message is easy to avoid because we do not need to process the .edmx file with a build provider in MVC. Simply add the following configuration into the root level web.config, and all will be well.

<system.web>               
  <compilation debug="true" targetFramework="4.0">
    <buildProviders>
      <remove extension=".edmx"/>
    </buildProviders>
    ...

Happy building!