IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

Razor Tip #2: Output Text in Code Context

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:

Razor Tip #2

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:
    Razor Tip #2
  • 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:
    Razor Tip #2
  • 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.
    Razor Tip #2

All the best,
Shay.



Razor Tip #1: Explicitly Stating Statement Boundaries

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:

image

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:

image

You can also use the parentheses trick to output small code statements like these:

image 

All the best,
Shay.