ASP.NET Razor Code Blocks: Embedding C# Logic in Your Views
Learn how to use code blocks in ASP.NET Razor to execute C# code within your view files and dynamically generate HTML content. This tutorial explains the syntax of Razor code blocks, implicit transitions between C# and HTML, and provides examples demonstrating their use in creating dynamic web pages.
ASP.NET Razor Code Blocks
Introduction to Razor Code Blocks
In ASP.NET Razor, code blocks are used to enclose C# statements within your view files. These blocks are not directly rendered as HTML; instead, the C# code within them is executed by the server, and the results can then be incorporated into the final HTML output. Code blocks begin with the `@` symbol followed by curly braces `{}`.
Example: A Simple Code Block
This example shows a basic code block that declares a variable and displays its value.
Razor Code (Index.cshtml)
@{
Layout = null;
var name = "John";
}
<p>Index</p>
<p>My name is: @name</p>
Output
(A screenshot showing the rendered output "Index My name is: John" would be included here.)
Implicit Transitions in Razor Code Blocks
Within a Razor code block, C# is the default language. However, if you write HTML code within a code block, it will be rendered as HTML. This is called an implicit transition. Razor automatically switches between C# and HTML rendering based on the context.
Razor Code (Index.cshtml)
@{
Layout = null;
}
<p>Index</p>
@{
var name = "JavaTpoint";
<p>Welcome to the @name</p>
}
Output
(A screenshot showing the rendered output "Index Welcome to the JavaTpoint" would be included here.)
Explicit Delimited Transitions
For more complex scenarios, you can explicitly define a section of HTML within a code block using the `<text>` tag. This is necessary to avoid compilation errors if you have HTML code within a C# code block that needs to be rendered directly as HTML.
Razor Code (Index.cshtml)
@{
Layout = null;
}
<p>Index</p>
@for (var i = 0; i < 5; i++)
{
<text><p>i = @i</p></text>
}
Output
(A screenshot showing the rendered output "Index i = 0, i = 1, i = 2, i = 3, i = 4" would be included here.)