Two Razor View Errors You Might Recognize

DZone 's Guide to

Two Razor View Errors You Might Recognize

Recently, I struggled for some time with some strange Razor views' behaviors I couldn’t understand. Allow me to share them with you and provide the solutions I came up with.

· Web Dev Zone ·
Free Resource

Recently, I went back to developing websites with ASP.NET MVC (after quite some time in SPA and Web API), and I struggled for some time with some strange Razor views' behaviors I couldn’t understand. Here are some of them. I 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 brackets. This confuses the Razor interpreter so much that it thinks there is a 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, it thinks <DateTime> is an HTML tag and wants you to close it.


The solution is pretty simple: just put everything inside some brackets, 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 the body is rendered, for every view, and you don’t have to add it to each view manually.

That’s all for now.

asp.net mvc, razor syntax

Published at DZone with permission of Simone Chiaretta , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}