Razor Tip #1

Thursday, January 6, 2011

The Razor parser is smart. For example, if you want to display an email address, you can enter the following:

<p>
    Serial@Model.com
</p>

... and Razor will happily output Serial@Model.com into the output - it recognizes the email address.

But what if you want to output a serial number?

<p>
    Serial@Model.SerialNumber
</p>

Unfortunately, Razor still thinks you have an email address and outputs "Serial@Model.SerialNumber". In a few rare cases you have to be more explicit and let the parser know where the C# code begins and ends.

<p>
    <text>Serial</text>@Model.SerialNumber
</p>

But a prettier approach is to use an “explicit code nugget” with parentheses:

<p>
    Serial@(Model.SerialNumber)
</p>

Comments
Shahnawaz Thursday, January 6, 2011
Nice tip!

Waiting for your next .net tip(s).

Thanks!
gravatar Eber Irigoyen Thursday, January 6, 2011
won't that omit the @ in the last example?
gravatar Eber Irigoyen Thursday, January 6, 2011
nevermind, that's what you want
gravatar scott Thursday, January 6, 2011
@Eber - right, trying to display:
"Serial779-332X"
luke Wednesday, January 19, 2011
If you did want an @ you can escape the @ by entering @@

so would have:
Serial@@@(Model.SerialNumber)
gravatar scott Wednesday, January 19, 2011
@luke: Good one.
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!