Razor syntax is a simple, clean, and powerful way to embed server-side code within HTML in web applications, primarily used with ASP.NET. It allows developers to write dynamic web pages with HTML and C# code together, making it easy to generate dynamic content on the server and render it in the browser.
Razor was introduced by Microsoft as part of the ASP.NET MVC framework and has since become a key part of ASP.NET Core, used for building web applications.
Here’s an overview of Razor syntax:
Basic Syntax: Razor code is embedded inside HTML using the @ symbol. Anything that starts with the "@" symbol is interpreted as C# code.
<h1>@DateTime.Now</h1>
This will display the current date and time on the web page.Variables: Razor allows you to use C# variables directly in the HTML. You can declare variables in your Razor code and display their values in the HTML.
@var message = "Hello, Razor!"
<p>@message</p>
This will render: Hello, Razor! inside the <p> tag.Control Structures (Loops and Conditionals):
Razor supports control structures like if, else, for, foreach, and more, allowing you to add logic to your web pages.
If Statement:
@if (userIsLoggedIn)
{
<p>Welcome back!</p>
}
else
{
<p>Please log in.</p>
}
For Loop:
<ul>
@for (int i = 0; i < 5; i++)
{
<li>Item @i</li>
}
</ul>
This would generate a list with items numbered 0 to 4.
HTML and Razor Combined: Razor allows you to mix C# code with HTML, so you can dynamically generate parts of your page. You can write HTML code as usual, and embed Razor code wherever needed.
<ul>
@foreach(var product in products)
{
<li>@product.Name - $@product.Price</li>
}
</ul>
In this case, if you have a list of products, Razor will loop through them and display each product’s name and price in the list.Expressions: Razor allows you to evaluate C# expressions inside the page. These expressions are automatically rendered as HTML.
<p>The sum is: @5 + 3</p>
This will output: The sum is: 8.Inline Code Blocks:
Razor supports inline code blocks where you can put multiple lines of C# code inside { }.
@{
var userName = "Alice";
var greeting = "Hello, " + userName;
}
<p>@greeting</p>
This will render: Hello, Alice.In short, Razor syntax makes it easier for developers to create dynamic content for web applications by allowing them to combine HTML and C# in a clean, readable way. It’s designed to be simple and intuitive while offering powerful features for building complex web applications.
Open this section to load past papers