🔹 What is Razor View in ASP.NET Core MVC?
Razor View is the UI layer in an ASP.NET Core MVC application that dynamically generates HTML using C# code. It helps separate the presentation logic from the business logic.
✔ Razor View Files
.cshtml
files (e.g.,Index.cshtml
,Details.cshtml
)- Stored inside the
Views
folder in an MVC project - Uses Razor syntax (
@
) to embed C# inside HTML
🔹 Why Use Razor Views?
Feature | Benefit |
---|---|
✅ Combines HTML & C# | Easily generate dynamic content in views |
✅ Fast & Lightweight | Razor is optimized for performance |
✅ Separation of Concerns | Keeps UI separate from business logic |
✅ Supports Layouts & Partial Views | Reusable components make development efficient |
✅ Works with Model Binding | Displays data from controllers directly |
🔹 Example: Razor View (Index.cshtml
)
@model List<Product> <!-- Specifies model type -->
<h2>Product List</h2>
<table class="table">
<tr>
<th>Name</th>
<th>Price</th>
</tr>
@foreach (var item in Model) // Looping through model data
{
<tr>
<td>@item.Name</td> <!-- Razor syntax to display data -->
<td>@item.Price</td>
</tr>
}
</table>
✔ Uses @model
to pass data from Controller
✔ Uses @foreach
to loop through items
✔ Renders HTML dynamically based on model data
🔹 How Razor Views Work in MVC?
- Controller returns a View
- View (
Index.cshtml
) uses Razor to display data - Browser renders the generated HTML page
🔹 Razor Syntax Features
Syntax | Description | Example |
---|---|---|
@Model.Property | Access model data | @Model.Name |
@{} | Inline C# code block | @{ var x = 10; } |
@if / @foreach | Conditional logic & loops | @if(Model.Age > 18) { ... } |
@Html.ActionLink() | Generate links dynamically | @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
🔹 Layouts & Partial Views (Code Reusability)
✔ _Layout.cshtml
(Common UI for all pages)
- Located in
Views/Shared/
- Contains header, footer, and navigation
<!DOCTYPE html>
<html>
<head>
<title>@ViewData["Title"]</title>
</head>
<body>
<header>Welcome to My App</header>
<div>
@RenderBody() <!-- Inserts content from other views -->
</div>
<footer>© 2025 MyApp</footer>
</body>
</html>
- Other pages inherit this using:
🔹 Summary
✅ Razor Views generate dynamic HTML in ASP.NET Core MVC
✅ Uses Razor syntax (@
) to mix C# with HTML
✅ Supports Layouts & Partial Views for code reuse
✅ Works with Model-View-Controller (MVC) architecture
No comments:
Post a Comment