WebPages Razor
The Razor syntax is what makes ASP.NET Web Pages so powerful yet simple. It blends server-side code (C# or VB) into HTML with minimal fuss, letting you quickly build dynamic, data-driven sites.
Key Topics
Razor Basics
In Razor, server-side statements start with @
. For instance, writing @DateTime.Now
in an HTML page will render the current date and time. Razor automatically detects whether you're writing a single statement or a block of code.
Inline Code
Example
<p>The current time is: @DateTime.Now</p>
Output
Explanation: Razor recognizes @DateTime.Now
as a single inline C# statement. When processed, it injects the value into the HTML, displaying the server's current date and time.
Code Blocks
For more complex logic, you can use code blocks @{ }
to declare variables, run loops, or perform conditionals before rendering them in the HTML.
Example
@{
var cities = new List<string> { "London", "New York", "Tokyo" };
}
<ul>
@foreach (var city in cities)
{
<li>@city</li>
}
</ul>
Output
- London
- New York
- Tokyo
Explanation: By declaring a C# list in a code block, you can iterate over it using an @foreach
loop. Razor injects the loop results directly into the HTML list.
Key Takeaways
- Razor syntax allows inline and block-based server-side code.
- It makes embedding dynamic data in HTML extremely straightforward.
- Code blocks (
@{ }
) handle more complex logic, loops, and conditionals.