Razor, the new ASP.NET MVC view engine is incredible. I like it. A LOT. Great work Microsoft!
In this series of posts I’m sharing some handy tips and tricks that can enhance your experience with this new view engine. Enjoy!
Razor is the place where HTML and C# live together in harmony. This is, in my opinion, one of the things that make razor the great view engine that it is. However, there’s a fly in the ointment. Assume you want to output “Good Morning!” if the hour is between 6AM and 9AM:
But oh no! Razor thinks “Good Morning!” is code!
Razor has a special solution for that problem. Three different solutions for the matter of fact:
- Writing the text inside an HTML element – razor knows to differentiate between C# and HTML so if you wrap the text with an HTML element, everything will work as expected:
- Adding the “@:” symbol at the beginning of the line – using this symbol will tell razor that this line is an output line and should not be treated as code:
- Using the special <text></text> element – when you want to output several lines within code context, it becomes irritating to use the “@:” symbol… For that you’ve got the special <text></text> element which tell razor that its content is to be outputted as HTML. Notice that the <text> element will not be outputted to the final HTML output.
All the best,