Razor syntax in ASP.NET 8 offers a range of advanced features that enhance the development experience for building dynamic web pages. Here’s a look at some of these advanced features and how they can be used to create more powerful and flexible web applications.
1. Tag Helpers
Tag Helpers provide a way to generate HTML markup in a more readable and maintainable way compared to traditional HTML helpers.
Examples:
Form Tag Helper: Simplifies the creation of forms with automatic model binding.
html<form asp-action="Create"> <div class="form-group"> <label asp-for="Name"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary">Create</button> </form>
Anchor Tag Helper: Generates
<a>
tags with URL routing.html<a asp-controller="Home" asp-action="Index">Home</a>
2. View Components
View Components are reusable components that encapsulate rendering logic. They are more powerful than partial views because they can have their own view model and can be invoked with parameters.
Example:
View Component Class:
csharp
public class RecentArticlesViewComponent : ViewComponent
{
private readonly IArticleService _articleService;
public RecentArticlesViewComponent(IArticleService articleService)
{
_articleService = articleService;
}
public IViewComponentResult Invoke(int count)
{
var recentArticles = _articleService.GetRecentArticles(count);
return View(recentArticles);
}
}
View Component View (Views/Shared/Components/RecentArticles/Default.cshtml
):
html
@model IEnumerable<Article>
<ul>
@foreach (var article in Model)
{
<li>@article.Title</li>
}
</ul>
Usage in a Razor Page:
html@await Component.InvokeAsync("RecentArticles", new { count = 5 })
3. Partial Views
Partial Views allow you to reuse view content across different views. They are useful for breaking down complex views into smaller, manageable pieces.
Example:
Partial View (Views/Shared/_ProductDetails.cshtml
):
html
@model Product
<h3>@Model.Name</h3>
<p>@Model.Description</p>
Usage in a Parent View:
html@Html.Partial("_ProductDetails", Model.Product)
4. Layout Pages
Layouts provide a consistent structure across your application’s views. They are similar to master pages in Web Forms.
Example:
Layout Page (Views/Shared/_Layout.cshtml
):
html
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<header>
<h1>My Application</h1>
</header>
<main>
@RenderBody()
</main>
<footer>
<p>© 2024</p>
</footer>
</body>
</html>
Usage in a View:
html
@{
Layout = "_Layout";
}
<h2>Welcome to My Application</h2>
<p>This is the home page.</p>
5. ViewData and ViewBag
ViewData
and ViewBag
are used to pass data from controllers to views. They are dynamic, allowing you to send data without creating a strongly-typed model.
Example:
Controller:
csharp
public IActionResult Index()
{
ViewBag.Message = "Welcome to My Application";
ViewData["Title"] = "Home Page";
return View();
}
View:
html
<h1>@ViewBag.Message</h1>
<h2>@ViewData["Title"]</h2>
6. Dynamic Content with @functions
Razor allows you to write C# code directly within your view using the @functions
directive. This is useful for creating inline methods or properties.
Example:
html
@functions {
public string GetGreeting()
{
return "Hello, Razor!";
}
}
<p>@GetGreeting()</p>
7. Tag Helper Attributes
Tag Helpers can have custom attributes to control their behavior. You can create your own Tag Helpers with attributes that you define.
Example:
Custom Tag Helper:
csharp
[HtmlTargetElement("my-button")]
public class MyButtonTagHelper : TagHelper
{
public string ButtonText { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "button";
output.Content.SetContent(ButtonText);
output.Attributes.SetAttribute("class", "btn btn-primary");
}
}
Usage in a View:
html
<my-button button-text="Click Me"></my-button>
8. Razor Pages with Page Model
Razor Pages in ASP.NET Core provide a more organized way to structure your web pages. Each page has a PageModel
class that handles the page's data and logic.
Example:
Page Model (Pages/Index.cshtml.cs
):
csharp
public class IndexModel : PageModel
{
public string Message { get; private set; }
public void OnGet()
{
Message = "Welcome to Razor Pages!";
}
}
Razor Page (Pages/Index.cshtml
):
html
@page
@model IndexModel
<h1>@Model.Message</h1>
9. Conditional Statements and Loops
Razor syntax supports C# conditional statements and loops directly within views, enabling dynamic content rendering.
Example:
html
@{
var isAuthenticated = User.Identity.IsAuthenticated;
}
@if (isAuthenticated)
{
<p>Welcome, @User.Identity.Name!</p>
}
else
{
<p>Please log in.</p>
}
10. View Components and Dependency Injection
View Components can use dependency injection to get services or repositories.
Example:
View Component:
csharp
public class LatestNewsViewComponent : ViewComponent
{
private readonly INewsService _newsService;
public LatestNewsViewComponent(INewsService newsService)
{
_newsService = newsService;
}
public IViewComponentResult Invoke()
{
var news = _newsService.GetLatestNews();
return View(news);
}
}
View Component View (Views/Shared/Components/LatestNews/Default.cshtml
):
html
@model IEnumerable<News>
<ul>
@foreach (var item in Model)
{
<li>@item.Title</li>
}
</ul>
Summary
- Tag Helpers: Enhance HTML element generation with server-side logic.
- View Components: Create reusable components with their own views and logic.
- Partial Views: Reuse view content across multiple views.
- Layout Pages: Provide a consistent structure for your views.
- ViewData and ViewBag: Pass data dynamically from controllers to views.
@functions
: Add inline C# code within Razor views.- Custom Tag Helpers: Create custom HTML tags with specific attributes.
- Razor Pages with Page Model: Organize web pages with separate page models.
- Conditional Statements and Loops: Render dynamic content with Razor syntax.
- View Components and Dependency Injection: Use dependency injection within View Components.
These advanced Razor features help streamline development, improve code organization, and enhance the maintainability of your ASP.NET 8 applications.