Welcome to this comprehensive guide on Razor Syntax, a powerful feature of ASP.NET that simplifies HTML and server-side code! In this tutorial, we'll dive deep into the world of Razor, covering everything from the basics to advanced examples.
Razor Syntax is a template engine used in ASP.NET to write HTML markup with embedded C# code. It makes it easier to create dynamic web pages by reducing the amount of server-side code required.
Let's start by creating a new ASP.NET Core Web Application:
dotnet new webapp -n MyFirstRazorAppNavigate to the new project folder:
cd MyFirstRazorAppNow, let's create a simple Razor page:
dotnet add page -n WelcomeOpen the newly created Pages/Welcome.cshtml file. You'll see a mix of HTML and C# code. Let's break it down:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome to ASP.NET Core!</h1>
</body>
</html>In the @{ ... } block, we're writing C# code that will be executed on the server. The rest is plain HTML.
You can declare and use variables in your Razor pages:
@{
int myNumber = 10;
}
<h1>My number is @myNumber</h1>Razor supports basic loops like foreach:
@{
int[] numbers = { 1, 2, 3, 4, 5 };
}
<ul>
@foreach (int number in numbers)
{
<li>@number</li>
}
</ul>Use if, else, and else if to control the flow of your code:
@{
int myNumber = 10;
}
@if (myNumber > 5)
{
<h1>The number is greater than 5.</h1>
}
else
{
<h1>The number is less than or equal to 5.</h1>
}@{ ... }@Html.Raw()@code blocks for complex C# codeWhat does the `@{ ... }` block represent in Razor Syntax?
Partials are reusable sections of HTML and Razor code. They can be used to separate common layout elements across multiple pages:
@using MyNamespace
@{
Layout = null;
}
<h1>Header</h1>
<div class="nav">Navbar</div>
<div class="content">
@RenderBody()
</div>
<footer>Footer</footer>In this example, we've created a _Layout.cshtml partial that includes a common header, navbar, content area, and footer. We can include this partial in our pages:
@page
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@include "./_Layout"
<h1>Welcome to My Page</h1>
<p>This is my page content.</p>Tag Helpers are custom HTML tags that can generate server-side code when they are rendered. They are a great way to simplify complex server-side logic:
<form asp-action="Submit" method="post">
<div>
<label for="name">Name:</label>
<input asp-for="Name" />
</div>
<button type="submit">Submit</button>
</form>In this example, we've used the asp-action and asp-for tag helpers to generate the appropriate server-side code for a form submission.
What is the purpose of a partial in Razor Syntax?
That's it for this tutorial on Razor Syntax in ASP.NET! Now, you're well-equipped to create dynamic web pages using Razor. Happy coding! 🎉