Compile Views in Asp.Net MVC 3 with Visual Studio

Why compiled views?

First of all I prefer VS.NET to compile the cshtml code at build time because it will notice syntax errors like on any .cs file. Syntax errors are most important when I have to do a quick check-in of all my sources to repository and I need to make sure I will not crash the next test build. On a default project the views are parsed and compiled at runtime when you fist navigate to the url with your browser, in other word the load time of an action will take longer because of the compiler. I prefer to wait a little longer for Visual Studio to check and compile my views then to wait for each one while debugging.


How to

Fist step is to edit the .csproj file and set the MvcBuildViews value to true. This setting was available since MVC 1 and it works on aspx  and cshtml as well.  There are lots of articles on the web about this, all you have to do is unload or close the mvc project in vs.net, edit the .cspoj file with vs.net or any other xml editor, locate <MvcBuildViews>  and change the value to true.

.csproj
<MvcBuildViews>true</MvcBuildViews>

When you’ll fist build the project if you have a .edmx file inside a MsBuild error will pop-up about EntityDesignerBuildProvider assembly. In order to fix this error open your project web.config and tell MsBuild that it should skip the edmx file from compilation:

Web.config
<compilation debug="true" targetFramework="4.0">
  <buildProviders>
    <remove extension=".edmx"/>
  </buildProviders>

For more information on this topic check out these blog posts from Malcolm Sheridan and  K. Scott Allen

PS

Some times Visual Studio will fail to build with an error regarding IIS, in order to fix it, delete the content of the Obj/Debug folder or run the “Clean” command on your project.

5 Responses to Compile Views in Asp.Net MVC 3 with Visual Studio
  1. kk Reply

    Short and sweet! Thank you

  2. Jan C. de Graaf Reply

    I get the following compile error with VS210, MVC3:

    It is an error to use a section registered as allowDefinition=’MachineToApplication’ beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

    Any ideas?

  3. Jan C. de Graaf Reply

    Already solved; I had to do a clean-by-hand of the obj/release/bin folders. VS’s clean was not enough.

  4. eka808 Reply

    Exactly what i need ! thank you !!!

  5. Svekl Reply

    Thank you! I was missing this feature.
    But project gave compiling error about Entity.Design, so i got to add this line to web.config:

Leave a Reply

Your email address will not be published. Please enter your name, email and a comment.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>