Outputting static text with the ASP.NET Razor view engine

Posted: (EET/GMT+2)

 

If you are using the latest version of ASP.NET MVC, it is pretty likely you've also started using the Razor view engine. Since everybody is comparatively new to Razor in production systems, I thought I'd share a simple tip on how to output static text from within Razor view pages, for the the .CSHTML files.

In Razor, a code block starts with the @ sign, and in the C# version, you can also write complete code blocks with the @{ } construct. But if you use such a multi-line code construct, how do you output static text within it?

Of course, you could use the canonical Response.Write method, but that's a bit tacky in otherwise very smooth Razor view pages. A better alternative is the @: construct, which indicates to Razor that the next symbol will be static text, and will be outputted as is (with html encoding).

If you instead want to output bigger amounts of text, such as a few sentences or even multiple lines, you can use the <text> tag. Whenever the Razor engine parses the code and finds a <text> tag, it takes everything between and the starting and ending tag and outputs them as literal text.