- Posted by Shay Friedman on April 21, 2011
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!
The Problem
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!
The Solution
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,
Shay.
- Posted by Shay Friedman on April 18, 2011
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 going to share some handy tips and tricks that can enhance your experience with this new view engine. Enjoy!
The Problem
You have to output a variable value and add some markup content immediately after it. For example, assume you have a variable holding a value representing a font size and you want to output it inside a style attribute, as follows:

But oh no! Razor can’t tell the difference between our fontSize variable and the “px” text that follows it so it will go look for a variable named “fontSizepx”!
The Solution
To solve the issue, we need to explicitly tell Razor where the variable name ends, or in more general terms – where the statement starts and ends. We do that by putting the variable name between parentheses:

You can also use the parentheses trick to output small code statements like these:
All the best,
Shay.