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.



Comments (1) -

Hey, thanks a bunch for the <text></text> tip. I had always wrapped HTML in a span but I ran into a situation today where I needed to conditionally add a css style and your solution worked great. Thanks again!

Example usage (Yeah, it's weird but it works):
<li class="list" style="width:100%; @if(count == 1){ <text> margin-top: -25px;</text>}">

Reply

Pingbacks and trackbacks (1)+

Add comment