Tuesday, February 25, 2025

Razor View

 

🔹 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.cshtmlDetails.cshtml)
  • Stored inside the Views folder in an MVC project
  • Uses Razor syntax (@) to embed C# inside HTML

🔹 Why Use Razor Views?

FeatureBenefit
✅ Combines HTML & C#Easily generate dynamic content in views
✅ Fast & LightweightRazor is optimized for performance
✅ Separation of ConcernsKeeps UI separate from business logic
✅ Supports Layouts & Partial ViewsReusable components make development efficient
✅ Works with Model BindingDisplays 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?

  1. Controller returns a View
    csharp
    public IActionResult Index() { var products = _productRepository.GetAll(); return View(products); // Pass data to View }
  2. View (Index.cshtml) uses Razor to display data
  3. Browser renders the generated HTML page

🔹 Razor Syntax Features

SyntaxDescriptionExample
@Model.PropertyAccess model data@Model.Name
@{}Inline C# code block@{ var x = 10; }
@if / @foreachConditional 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:
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }

🔹 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