Lately I went back developing web sites with ASP.NET MVC (after quite some time in SPA and Web API), and I struggled for some time with some strange Razor views behaviours I couldn’t understand. Here are some of them. Hope this post will help you save some time in case you have the same problems.
Using Generics in Razor views
Generics’ syntax has a peculiarity that might interfere when writing inline inside HTML tags: the use of angular brakets. This confuses the Razor interpreter so much that it things there is missing closing tag.
For example, when trying to write @Model.GetPropertyValue<DateTime>(“date”) you’ll get an error and Visual Studio will show some wiggle with the following alert.
Basically he thinks <DateTime> is an HTML tag and wants you to close it.
Solution is pretty simple: just put everything inside some brakets, like @(Model.GetPropertyValue<DateTime>(“date”))
Order of execution of Body and Layout views
I wanted to set the current UI Culture of my pages with every request, so I wrote a partial view that I included at the top of my layout view: all text in the layout was correctly translated, while the text coming from the Body was not.
After some digging I realized that the order of execution of a Razor view starts with the view itself (which renders the body) and then goes on with the Layout. So my UICulture was set after the body was rendered. So I had to move the partial view that was setting the culture at the top of the “main” view.
If you have many views, just put all initialization code inside a view called _ViewStart.cshtml. This way the code is executed before body is rendered, for every view, and you don’t have to add it to each view manually.
That’s all for now.