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.
Join the DZone community and get the full member experience.
Join For Freerecently, 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.
Published at DZone with permission of Simone Chiaretta, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments