Home » ASP.Net Razor Code Blocks

ASP.Net Razor Code Blocks

by Online Tutorials Library

ASP.NET Razor Code Blocks

Code block is used to enclose C# code statements. It starts with @ (at) character and is enclosed by {} (curly braces). Unlike expressions, C# code inside code blocks is not rendered. The default language in a code block is C#, but we can transit back to HTML. HTML within a code block will be rendered as HTML.


Example

// Index.cshtml

It produces the following output.

ASP Razor code blocks 1


Implicit transitions

C# is default language in Razor code block. HTML written within code block is rendered as HTML, this is called implicit transition. Razor code blocks implicit transitions HTML code and render to the view page.

In the following code, HTML is written and it executes without error.

// Index.cshtml

It produces the following output.

ASP Razor code blocks 2


Explicit delimited transition

Sometimes, when we define a sub-section of a code block that should render HTML, surround the characters to be rendered with the Razor <text> tag.

It is mandate to use <text> tag. Otherwise, it throws a compile time error. See the following code.

// Index.cshtml

It produces the following output.

ASP Razor code blocks 3

You may also like