aspnet
  1. aspnet-razor-code-blocks

Razor Code Blocks in ASP.NET Razor

Razor is an ASP.NET programming syntax used to create dynamic HTML pages and templates. Razor code blocks are used to embed C# code within an HTML file.

Syntax

Razor code blocks start with the @ symbol followed by either { and } or ( and ) to define the code block type. The two main types of code blocks are expressions and statements.

Expression Code Block

An expression code block is used to evaluate and display expressions within Razor views.

@{ 
    // C# code goes here
    int x = 4;
    int y = 6;
}

<p>The sum of @x and @y is @(x + y).</p>

Statement Code Block

A statement code block is used to execute C# statements within Razor views.

@for(int i = 0; i < 5; i++)
{
    <p>The value of i is @i</p>
}

Example

Here is an example of using a Razor code block to display data from a database:

@if (Model.Count > 0) 
{
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model) 
            {
                <tr>
                    <td>@item.Name</td>
                    <td>@item.Age</td>
                </tr>
            }
        </tbody>
    </table>
}
else
{
    <p>No data available.</p>
}

Output

The output of a Razor code block can be anything, from plain text to full HTML pages. In the example above, the output is an HTML table displaying records from a database if there is any data, or a message indicating that there is no data.

Explanation

Razor code blocks can be used to inject C# logic into HTML pages without having to switch between multiple programming languages. The syntax is concise and easy to read, making it simple to work with.

Use

Razor code blocks are often used in ASP.NET web applications to dynamically generate HTML pages based on data from a database or external source. They can be used to create lists, tables, or custom user interfaces. Razor code blocks can also be used to handle user input and perform calculations.

Important Points

  • Razor code blocks allow developers to embed C# logic within HTML templates.
  • There are two types of code blocks: expression and statement.
  • Expression code blocks display the output of an expression within the HTML template.
  • Statement code blocks execute C# statements within the HTML template.
  • Razor code blocks are often used in ASP.NET web applications to generate dynamic HTML pages.

Summary

Razor code blocks are a powerful feature of ASP.NET Razor that allow developers to seamlessly inject C# logic into HTML templates. They make it easy to generate dynamic HTML content, handle user input, and perform calculations. By using Razor code blocks, developers can create clean, concise, and maintainable code that is easy to read and understand.

Published on: