ASP.NET Razor Code Expressions: Dynamically Generating HTML Content
Learn how to use code expressions in ASP.NET Razor to embed C# code directly within your HTML for dynamic content generation. This tutorial explains the syntax of Razor expressions, demonstrates their use in inserting variable values and expression results into HTML, and shows how to create dynamic web pages.
ASP.NET Razor Code Expressions
Introduction to Razor Code Expressions
ASP.NET Razor allows you to embed C# code directly within your HTML, making it easy to generate dynamic content. Razor code expressions are a concise way to insert the values of C# expressions directly into your HTML. These expressions are evaluated by the server, and their results are inserted into the rendered HTML sent to the client's browser. Razor expressions begin with the `@` symbol.
Example: A Simple Razor Code Expression
This example shows a simple Razor expression that displays the value of a C# variable:
Razor Code (Index.cshtml)
@{
Layout = null;
var coursename = "Java Collection";
}
<p>Index</p>
<p>I want to learn @coursename</p>
Output
(A screenshot showing the rendered output "Index I want to learn Java Collection" would be included here.)
Implicit Razor Expressions
Implicit Razor expressions begin with the `@` symbol followed directly by a C# expression. The result of the expression is inserted into the HTML.
Razor Code (Index.cshtml)
@{
Layout = null;
}
<p>Index</p>
<p>Current Time is: @DateTime.Now.ToString("T")</p>
Output
(A screenshot showing the rendered output "Index Current Time is: HH:mm:ss" (where HH:mm:ss is the current time) would be included here.)
Explicit Razor Expressions
For more complex expressions or to avoid potential conflicts, you can use explicit Razor expressions by enclosing the C# code in parentheses. This is particularly useful when combining text and expressions.
Razor Code (Index.cshtml)
@{
Layout = null;
}
<p>Index</p>
<p>2 + 5 = @(2 + 5)</p>
Output
(A screenshot showing the rendered output "Index 2 + 5 = 7" would be included here.)
Razor Expression Encoding
Razor provides automatic encoding to prevent cross-site scripting (XSS) vulnerabilities. If a user enters potentially harmful script code, Razor will automatically encode it, preventing the code from being executed. This enhances security.
Razor Code (Index.cshtml) - Encoding Example
@{
Layout = null;
}
<p>Index</p>
<p>@Html.Raw("<script>alert('This is encoded')</script>")</p>
Output
(A screenshot showing the rendered output "Index <script>alert('This is encoded')</script>"—showing that the script is rendered as plain text and not executed—would be included here.)