Adrian Grigore

ASP.NET MVC Tip #2: Turn on compile-time View Checking

In ASP.NET, ASP.NET MVC on May 3, 2009 at 16:01

I like the compiler to catch as many errors as possible before I start debugging or release my application. This also applies to code nuggets in ASP.NET MVC views, especially since these are not easily unit-testable. But views are not validated at compilation, at least not when using the standard settings for ASP.NET MVC projects.

Tools like Resharper can notify you of syntax errors within your views, but you can still build the project and not get a single error. Instead, your application will crash when trying to evaluate the buggy view.

Fortunately you can easily make Visual Studio compile your views along with the rest of your code. The only downside is that your project will build a bit slower, but if this bothers you during development you can also enable this feature on a per configuration basis. For example you may want to compile your views in Release mode, but not in your Debug configuration , so you have the extra safety of compile-time view checking before releasing a new version, but you still get lightning-fast compilation times while developing.

Please proceed as follows to turn on compile time view compilation:

  1. Open your .csproject or .vbproject file in a text editor of your choice. It’s just a simple xml file, which is why any editor will do fine.
  2. Locate the <PropertyGroup> element that belongs to the configuration you would like to alter.
  3. Within this PropertyGroup, add an additional element with “true” as its text value.

For example, this will turn on view compilation in my project’s Release configuration:

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

That’s it! The next time one of your views has compile-time errors, these will be reported when building your application.

One last thing: You need to repeat this procedure for all configurations you might create in the future if you want your views to be checked in those configurations as well. Even if you tell Visual Studio to copy settings from an existing configuration where this tag is already set to true, the MvcBuildViews tag is not copied by Visual Studio.

Edit: As some readers pointed out, your project’s compilation time will increase after turning on view compilation. For this reason, I have recently switched it off for the debug configuration of my current project. However, compile-time view compilation is still tremendously useful before releasing a new version. Or perhaps even before submitting a new revision to your source control server. It can catch a lot of different errors this way, especially if you are using the new ASP.NET MVC strongly typed Html helpers.

kick it on DotNetKicks.com

  1. ASP.NET MVC Tip: Turn on compile-time View Checking | devermind.com…

    DotNetBurner – burning hot .net content…

  2. I made this change in a v1 MVC project, but it doesn’t seem to be working. I adding some bad code: , but no compile time errors. Am I missing something?

  3. Seems my code was stripped out, basically: Html.MyActionLink(), which doesn’t exist.

  4. @Steve: I just tested this again by creating a new project and adding the Element as described above.

    My guess is that you might have added the tag to the wrong PropertyGroup element. When you create a new MVC project, there are two configurations, but three different PropertyGroups. I’m not sure what the first one is for, but the second one is for the Debug configuration and the third for Release.

  5. […] ASP.NET MVC Tip: Turn on compile-time View Checking (Adrian Grigore) […]

  6. Hey, the first one is general and applies to all builds, both debug and release. I put it in there. What language MVC project are you creating? I’m using C# for the v1 release of .NET MVC.

    Thanks!

  7. I am using C# and .NET MVC with Visual Studio 2008 Team System SP1.

    Perhaps you could create a new MVC project just to test this, then add the tag, add a typo in a view and then compile. Just to find if it is something that goes wrong in general on your system or something related to your project in particular.

  8. Oh, and I’d also try putting it it one of the other two sections (Debug or Release only) if everything else fails.

  9. I only recently discovered this the other day and have been working with it for two days now. I hate it! Sure it picks up the view errors on build but it makes the build so so slow. CTRL+SHIFT+B is maybe a 100-a-day operation for me sometimes (coz sometimes just relying on the background thread checking in VS is simply too slow) but with this post-build view checking – it can turn a 3-4second process into a 1-2minute deal. Way too long!

    I went back to the ‘old way’ late this afternoon. Sure i may miss some errors in my views and only discover them at runtime.. but i’ve managed that way till now.. and the more i move functionality into helpers the less code there is in the view for problems. It’s kool to know it’s there when you are pulling your hair with a bug you cant find.. or build-completeness.. but for everyday use.. and chewing thru work – its a pain. Sorry, not a fan. 😦

  10. Matt,

    As described in my article, you can add compile-time checking on a per-configuration base only. This way you can keep blazing-fast compilation times in your debug configuration and take advantage of compile-time checking in release mode.

  11. […] Tip: Turn on compile-time View Checking: A nice post from Adrian Grigore who demonstrates how to easily enable compile-time checking of your ASP.NET MVC view files. […]

  12. […] Tip: Turn on compile-time View Checking: A nice post from Adrian Grigore who demonstrates how to easily enable compile-time checking of your ASP.NET MVC view files. […]

  13. […] ASP.NET MVC Tip: Turn on compile-time View Checking | devermind.com […]

  14. Rather than spend time converting VS2010 to use WPF for the seemingly sole purpose of giving us gradient code highlighting, why didn’t Microsoft spend a bit of time speed-optimizing the website compiler?? I just don’t understand why we’re stuck with this dog of a compiler after THREE major revisions of the IDE!! My hard drive just cranks and cranks and cranks and cranks and cranks … did Microsoft tell the website compiler to bypass the cache explicitly?? I’m at a loss…

  15. […] ASP.NET MVC Tip: Turn on compile-time View Checking | devermind.com […]

  16. […] Tip: Turn on compile-time View Checking: Adrian Grigore的一篇好贴,示范如何轻松地启用对ASP.NET MVC视图文件的编译时检查。 […]

  17. […] der Stelle möchte ich mich bei Daniel Richter für den Tipp danken. Im Web bin ich bereits auf diesen Post gestoßen der dasselbe vorschlägt, falls meine Erklärung nicht verständlich […]

  18. […] ASP.NET MVC Tip: Turn on compile-time View Checking | devermind.com […]

  19. […] ASP.NET MVC Tip: Turn on compile-time View Checking | devermind.com […]

  20. Thanks for the useful info. It’s so interesting

  21. I think this is a good website. It give us chance to communicate with the developer face to face ! Like me as a beginner , We need this kind of platform very much. l hope Adrian Grigore can answer questions in time for everyone! Thank you very much!!!!!!!!!

  22. Thanks for your kind comments, Javen :-). I’ll do my best to answer all questions coming up regarding my articles.

  23. […] Tip: Turn on compile-time View Checking: A nice post from Adrian Grigore who demonstrates how to easily enable compile-time checking of your ASP.NET MVC view files. […]

  24. I also had problems making this work until I added the following code:

  25. what we did was to put this as an option in our CI build

    we have build views as false in the project file

    false

    and within the msbuild file which runs within the CI server we turn it back on again

    This means we have the check that the views build correctly performed on the build server rather than slowing developers down every time a build is performed.

  26. […] Truco: Activar la comprovación de la vista en tiempo de compilación: Un post de Adrian Grigore que muestra cómo podemos activar la comprovación en tiempo de compilacion de los archivos de vistas de ASP.NET MVC. […]

  27. It’s good that this option is available, some might say essential. Thanks for pointing it out. Why is it hidden?

    I found a little problem: if the project’s folder name is different to the project’s name then an error occurs when building the project. The error message, raised by the ASPNETCOMPILER, looks like:
    The directory ‘<>/<>’ doesn’t exist.
    Obviously there’s a work around.

  28. […] Tip: Turn on compile-time View Checking: A nice post from Adrian Grigore who demonstrates how to easily enable compile-time checking of your ASP.NET MVC view files. […]

  29. This is very helpful information.

    At the starting of project we did many changes to name spaces ,created stronged types views,later changed the type name space etc…We were only able to find these during runtime only.

    This tip helped in finding those at compile time..

    Good stuff Adrian.

  30. […] expressions when referencing models/viewmodels passed to a view template.  This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to runtime), and also enables better code […]

  31. Очень вам признателен, на самом деле полезная информация.

  32. […] 大家对ASP.NET MVC 2要求的一个常用特性是,要我们支持强类型的HTML辅助方法,这样的辅助方法使用 lambda 表达式来引用传到视图模板中的模型或视图模型。这可以促成更好的编译时视图检查(可以在编译时发现缺陷,而不是在运行时),还可以促成视图模板中更好的代码intellisense支持。 […]

  33. […] expressions when referencing models/viewmodels passed to a view template.  This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to runtime), and also enables better code […]

  34. […] referenciam modelos/visões de modelo passados para um modelo de visão. Isso permite uma melhor verificação do código das visões no tempo de compilação (de modo que os erros podem ser encontrados em tempo de compilação em oposição ao tempo de […]

  35. […] referenciam modelos/visões de modelo passados para um modelo de visão. Isso permite uma melhor verificação do código das visões no tempo de compilação (de modo que os erros podem ser encontrados em tempo de compilação em oposição ao tempo de […]

  36. […] referenciam modelos/visões de modelo passados para um modelo de visão. Isso permite uma melhor verificação do código das visões no tempo de compilação (de modo que os erros podem ser encontrados em tempo de compilação em oposição ao tempo de […]

  37. […] expressions when referencing models/viewmodels passed to a view template.  This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to runtime), and also enables better code […]

  38. […] expresiones lambda cuando referencien a modelos y vistas a una plantilla. Esto permite una mejor revisión en tiempo de compilación de las vistas (de manera que se pueden encontrar errores en tiempo de compilación en lugar de en […]

  39. […] expressions when referencing models/viewmodels passed to a view template.  This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to runtime), and also enables better code […]

  40. […] expressions when referencing models/viewmodels passed to a view template.  This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to runtime), and also enables better code […]

  41. Crap, didn’t realise that would happen 🙂
    If I remove the li tags then the link works.

  42. […] expressions when referencing models/viewmodels passed to a view template.  This enables better compile-time checking of views (so that bugs can be found at build-time as opposed to runtime), and also enables better code […]

  43. This doesn’t work out of the box so to speak with VS2010, you get an error : 346 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.

  44. […] developers I talk to prefer to use strongly-typed views. Strong typing gives us intellisense and compiler errors.  But – is there a cost? Does strongly typing the view lead to a form of bad coupling between the […]

  45. Hi, I am currently working on an application that will be in different languages. One of these in German. when i run the app in en-US, I am able to get the AM or PM for the time using “hh:mm tt”, however when i switch the webconfig file to de-DE for the german information to be applied, I cannot get the AM or PM – I only get the time, eg, 3:04 instead of 3:04 PM.

    How do I overcome this challenge?

  46. @Roxanne: How is this related to this article?

  47. It isn’t really. Just a novice programmer seeking much needed assistance. Forgive me if I was out of place.

  48. @Roxanne: Have a look at stackoverflow.com . It’s a fantastic place to freely post questions such as this one and you usually get a reply within a few minutes.

  49. Thank you

  50. @Brandon : I have the same problem with vs2010 and mvc 2 , did you find the answer

  51. Hi Adrian, nice advice, will use it in my Relase deploys. However for debugging I’d rather go yet another step backwards – and even have the controllers and models uncompiled (for quick fix and refresh / repl – routines), but that is not possible at all, is it? (Inspired by working some with dynamic languages ofcourse).

    Thanks
    Jonas

  52. Hi Jonas,

    It would be a great feature, but unfortunately it is not possible. After all, C# has to be precompiled for IIS to run. On the bright side, the mantatory compilation does catch static errors, saving you time in some instances.

Leave a reply to Fred Cancel reply