Sure! Let's dive deep into Module 2.2: Views of the MVC architecture, specifically focusing on ASP.NET Core MVC. We'll cover each subtopic thoroughly, complete with explanations and code examples to help you understand and implement various view-related features effectively.
2.2. Views
Views in the MVC (Model-View-Controller) architecture are responsible for presenting data to the user. They define how the application's data is displayed, leveraging the Razor View Engine to blend HTML with server-side code seamlessly.
2.2.1. Introduction to Razor View Engine
What is Razor?
Razor is a markup syntax for embedding server-based code into web pages. It is designed to be clean and lightweight, allowing developers to write HTML markup with C# code seamlessly.
Combining C# Code with HTML
Razor allows you to embed C# code within HTML using a simple and readable syntax. This enables dynamic content generation based on server-side logic.
Razor Syntax Basics
- Code Blocks: Enclosed within
@{ }, allowing multiple lines of C# code.
- Expressions: Prefixed with
@, used to output values.
- Comments: Enclosed within
@* *@, ignored by the engine.
Using C# in Views
You can use variables, loops, and conditionals to control the rendered HTML.
Razor Syntax Examples
Code Block
@{
var currentTime = DateTime.Now;
}
<p>The current server time is @currentTime.</p>
Explanation:
- The
@{ } block defines a C# code section.
- The variable
currentTime is defined and then displayed in the HTML using @currentTime.
Expressions
<p>Hello, @Model.UserName!</p>
Explanation:
@Model.UserName inserts the UserName property from the model into the HTML.
Loops and Conditionals
<ul>
@foreach (var product in Model.Products)
{
<li>@product.Name - @product.Price.ToString("C")</li>
}
</ul>
@if (Model.IsAdmin)
{
<button>Edit</button>
}
else
{
<p>You do not have edit permissions.</p>
}
Explanation:
- The
foreach loop iterates over a collection of products, generating a list item for each.
- The
if-else conditionally renders content based on the IsAdmin property of the model.
2.2.2. Creating and Rendering Views
View Naming Conventions
In ASP.NET Core MVC, views are organized within the Views folder. Each controller has its own folder containing views related to its actions.
Example Structure:
/Views
/Product
Index.cshtml
Create.cshtml
Edit.cshtml
Details.cshtml
Delete.cshtml
/Shared
_Layout.cshtml
_ValidationScriptsPartial.cshtml
Naming Conventions:
- The view name should match the action method name.
- For example, the
Index action in ProductController corresponds to Index.cshtml in the Views/Product folder.
Returning Views from Controllers
In your controller, actions typically return views using the View() method.
Example Controller:
public class ProductController : Controller
{
// GET: Product
public IActionResult Index()
{
var products = _productService.GetAllProducts();
return View(products); // Passes the product list to the view
}
// GET: Product/Create
public IActionResult Create()
{
return View();
}
// POST: Product/Create
[HttpPost]
public IActionResult Create(Product model)
{
if (ModelState.IsValid)
{
_productService.AddProduct(model);
return RedirectToAction("Index");
}
return View(model);
}
}
Specifying View Names
By default, return View(); returns the view that matches the action name. You can specify a different view name if needed.
public IActionResult CustomView()
{
return View("SpecificViewName");
}
Passing Data to Views
There are several ways to pass data from a controller to a view:
-
ViewData
-
Definition: A dictionary object for passing data.
-
Usage:
public IActionResult Index()
{
ViewData["Message"] = "Welcome to the Product Page!";
return View();
}
<h1>@ViewData["Message"]</h1>
-
ViewBag
-
Definition: A dynamic wrapper around ViewData.
-
Usage:
public IActionResult Index()
{
ViewBag.Message = "Welcome to the Product Page!";
return View();
}
<h1>@ViewBag.Message</h1>
-
Strongly-Typed Models
-
Definition: Passing a model directly to the view for type safety and IntelliSense support.
-
Usage:
public IActionResult Index()
{
var products = _productService.GetAllProducts();
return View(products);
}
@model IEnumerable<Product>
<ul>
@foreach (var product in Model)
{
<li>@product.Name - @product.Price.ToString("C")</li>
}
</ul>
Recommendation: Prefer using strongly-typed models (@model) over ViewData or ViewBag for better type safety and maintainability.
2.2.3. Layouts and Sections
Creating a Layout Page
A layout defines the common structure for multiple views, such as headers, footers, and navigation menus.
Example: _Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewData["Title"] - My MVC App</title>
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav>
<!-- Navigation menu -->
<a href="/">Home</a> |
<a href="/Product">Products</a> |
<a href="/Contact">Contact</a>
</nav>
</header>
<div class="container">
@RenderBody()
</div>
<footer>
<p>© 2023 - My MVC App</p>
</footer>
@RenderSection("Scripts", required: false)
</body>
</html>
Explanation:
@RenderBody(): Placeholder for the main content of the view.
@RenderSection("Scripts", required: false): Placeholder for additional scripts defined in individual views.
Using Layouts in Views
To use the layout in a view, specify it using the @layout directive or set it in the _ViewStart.cshtml file.
Option 1: Specify Layout in View
@{
Layout = "_Layout";
}
<h2>Product List</h2>
<!-- View content -->
Option 2: Define in _ViewStart.cshtml
Create or modify _ViewStart.cshtml in the Views folder:
@{
Layout = "_Layout";
}
Explanation: Setting the layout in _ViewStart.cshtml applies it to all views unless overridden.
Defining Sections
Sections allow you to inject content into specific parts of the layout from individual views.
Example: Defining a Section in View
@{
Layout = "_Layout";
}
<h2>Product Details</h2>
<p>Product details go here.</p>
@section Scripts {
<script src="~/js/product-details.js"></script>
}
Explanation:
- The
Scripts section defined here will be rendered in the @RenderSection("Scripts", required: false) location of the layout.
2.2.4. Partial Views
Purpose of Partial Views
Partial views are reusable components that encapsulate specific UI elements, such as headers, footers, navigation menus, or forms. They help maintain DRY (Don't Repeat Yourself) principles by allowing you to reuse common UI snippets across multiple views.
Creating Partial Views
- Naming Convention: Partial view filenames typically start with an underscore
_ to differentiate them from regular views.
Example: _NavMenu.cshtml
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/Product">Products</a></li>
<li><a href="/About">About</a></li>
<li><a href="/Contact">Contact</a></li>
</ul>
</nav>
Rendering Partial Views
You can render a partial view using different helper methods:
-
@Html.Partial
@Html.Partial("_NavMenu")
-
@Html.RenderPartial
@{ Html.RenderPartial("_NavMenu"); }
-
@await Html.PartialAsync
@await Html.PartialAsync("_NavMenu")
-
@await Html.RenderPartialAsync
@{ await Html.RenderPartialAsync("_NavMenu"); }
-
Tag Helpers (ASP.NET Core)
<partial name="_NavMenu" />
Recommendation: Use the <partial> tag helper for cleaner syntax in ASP.NET Core.
Passing Data to Partial Views
Partial views can accept models or utilize ViewData/ViewBag.
Passing a Model:
@* Parent View *@
@model ProductViewModel
<partial name="_ProductDetails" model="Model.Product" />
@* _ProductDetails.cshtml *@
@model Product
<div>
<h3>@Model.Name</h3>
<p>@Model.Description</p>
<p>Price: @Model.Price.ToString("C")</p>
</div>
Using ViewData:
@* Parent View *@
@{
ViewData["Category"] = "Electronics";
}
<partial name="_CategoryInfo" />
@* _CategoryInfo.cshtml *@
<div>
<p>Category: @ViewData["Category"]</p>
</div>
2.2.5. Display and Editor Templates
Display Templates
Display templates define how specific data types or models are rendered for display purposes. They help maintain consistent formatting across the application.
Creating a Display Template:
-
Location: /Views/Shared/DisplayTemplates/Price.cshtml
-
Content:
@model decimal
<span class="price">@Model.ToString("C")</span>
Explanation: Formats decimal values as currency with appropriate styling.
-
Using the Display Template:
@model Product
<p>Price: @Html.DisplayFor(model => model.Price)</p>
Explanation: Automatically uses the Price.cshtml display template for the Price property.
Editor Templates
Editor templates define how specific data types or models are rendered for editing (input forms). They ensure consistency in form inputs across the application.
Creating an Editor Template:
-
Location: /Views/Shared/EditorTemplates/Date.cshtml
-
Content:
@model DateTime?
<input type="date" asp-for="." class="form-control" />
Explanation: Renders a date input field with appropriate attributes.
-
Using the Editor Template:
@model Product
<div class="form-group">
@Html.LabelFor(model => model.ReleaseDate)
@Html.EditorFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)
</div>
Explanation: Automatically uses the Date.cshtml editor template for the ReleaseDate property.
Benefits of Using Templates
- Consistency: Ensures uniform rendering across different views.
- Maintainability: Changes to a template affect all views using it.
- Reusability: Reduces code duplication by reusing common rendering logic.
2.2.6. Strongly-Typed Views
Advantages of Strongly-Typed Views
- IntelliSense Support: Enhanced coding experience with auto-completion and error checking.
- Type Safety: Compile-time checking reduces runtime errors.
- Clear Contracts: Defines explicit data structures expected by the view.
Specifying the Model Type
At the top of the view, declare the model type using the @model directive.
Example: Index.cshtml
@model IEnumerable<Product>
<h2>Product List</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach(var product in Model)
{
<tr>
<td>@product.Name</td>
<td>@product.Price.ToString("C")</td>
<td>@product.Category.Name</td>
<td>
<a href="/Product/Details/@product.Id">Details</a> |
<a href="/Product/Edit/@product.Id">Edit</a> |
<a href="/Product/Delete/@product.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Accessing Model Properties
Use the Model keyword to access properties of the passed model.
Example: Details.cshtml
@model Product
<h2>@Model.Name Details</h2>
<p><strong>Description:</strong> @Model.Description</p>
<p><strong>Price:</strong> @Model.Price.ToString("C")</p>
<p><strong>Category:</strong> @Model.Category.Name</p>
<a href="/Product/Edit/@Model.Id">Edit</a> |
<a href="/Product">Back to List</a>
Explanation:
- The view expects a
Product model.
- Accesses properties like
Name, Description, Price, and related Category.
2.2.7. HTML Helpers and Tag Helpers
ASP.NET Core MVC provides two main approaches to generate HTML content dynamically: HTML Helpers and Tag Helpers. Both aim to simplify HTML generation and enhance productivity, but they differ in syntax and usage.
HTML Helpers
HTML Helpers are methods that return HTML strings, allowing developers to generate HTML elements with server-side logic.
Common HTML Helpers:
Html.TextBoxFor()
Html.LabelFor()
Html.EditorFor()
Html.DisplayFor()
Html.ActionLink()
Html.DropDownListFor()
Example: Creating a Form with HTML Helpers
@model Product
<form asp-action="Create" method="post">
<div class="form-group">
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="form-group">
@Html.LabelFor(model => model.Price)
@Html.EditorFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</div>
<div class="form-group">
@Html.LabelFor(model => model.CategoryId, "Category")
@Html.DropDownListFor(model => model.CategoryId, (SelectList)ViewBag.Categories, "Select Category", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CategoryId)
</div>
<button type="submit" class="btn btn-primary">Create</button>
</form>
Explanation:
Html.LabelFor: Generates a <label> element for the specified property.
Html.TextBoxFor: Generates an <input type="text"> element.
Html.DropDownListFor: Generates a <select> element with options.
Html.ValidationMessageFor: Displays validation messages for the specified property.
Tag Helpers
Tag Helpers are a newer feature in ASP.NET Core that provide a more natural HTML-like syntax. They offer more intuitive syntax and integrate seamlessly with HTML editors.
Common Tag Helpers:
asp-for
asp-action
asp-controller
asp-route-*
asp-validation-for
Example: Creating a Form with Tag Helpers
@model Product
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CategoryId" class="control-label"></label>
<select asp-for="CategoryId" asp-items="ViewBag.Categories" class="form-control"></select>
<span asp-validation-for="CategoryId" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Create</button>
</form>
Explanation:
asp-for: Binds the input to the model property.
asp-items: Binds the <select> options to a list provided in ViewBag.
asp-validation-for: Displays validation messages.
Comparison and Best Practices
| Feature | HTML Helpers | Tag Helpers |
|---|
| Syntax | Method-based | Tag-based |
| Readability | Verbose, less HTML-like | More natural, HTML-like |
| IntelliSense | Limited | Better IntelliSense support in editors |
| Customization | Requires extension methods | Easier to customize with built-in features |
| Performance | Similar in most cases | Similar in most cases |
Recommendation: Prefer Tag Helpers for new projects due to their intuitive syntax and better integration with modern HTML practices.
Custom Tag Helpers
You can create custom Tag Helpers to encapsulate reusable HTML components with custom logic.
Example: Creating a Custom Tag Helper for a Bootstrap Alert
- Create the Tag Helper Class:
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace MyMvcApp.TagHelpers
{
[HtmlTargetElement("bootstrap-alert")]
public class BootstrapAlertTagHelper : TagHelper
{
public string Type { get; set; } = "info"; // default type
public string Message { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "div"; // Replaces <bootstrap-alert> with <div>
output.Attributes.SetAttribute("class", $"alert alert-{Type}");
output.Content.SetContent(Message);
}
}
}
- Register Tag Helpers:
In _ViewImports.cshtml, add the following line to register all Tag Helpers in the specified namespace:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, MyMvcApp
- Use the Custom Tag Helper in a View:
<bootstrap-alert type="success" message="Your product was created successfully!" />
Resulting HTML:
<div class="alert alert-success">
Your product was created successfully!
</div>
Explanation:
- The custom Tag Helper
BootstrapAlertTagHelper replaces the <bootstrap-alert> tag with a <div> containing the appropriate Bootstrap classes and message.
2.2.8. Bundling and Minification
Optimizing Static Files
Bundling and minification are techniques used to reduce the number of HTTP requests and the size of static files (like CSS and JavaScript), improving page load times and overall performance.
Bundling
Bundling combines multiple files into a single file, reducing the number of HTTP requests. For example, combining multiple CSS files into one.
Minification
Minification reduces the size of files by removing unnecessary characters (like whitespace, comments) without affecting functionality. It often includes renaming variables to shorter names.
Implementing Bundling and Minification in ASP.NET Core
ASP.NET Core provides built-in support for bundling and minification through various methods:
- Using Bundling Middleware (ASP.NET Core 3.1 and earlier)
- Using Task Runners (e.g., Gulp, Webpack)
- Using Libraries like LibMan (Library Manager)
Note: Modern ASP.NET Core projects often use tools like Webpack for more advanced scenarios.
Using LibMan (Library Manager)
LibMan is a lightweight tool to manage client-side libraries. It allows you to restore client-side files from libraries like CDNJS, unpkg, etc.
Example: Adding Bootstrap via LibMan
-
Add Library via Visual Studio:
- Right-click the project, select Add > Client-Side Library.
- Choose Provider (e.g., CDNJS).
- Select Library (e.g.,
twitter-bootstrap@5.3.0).
- Select the desired files (e.g.,
dist/css/bootstrap.min.css, dist/js/bootstrap.bundle.min.js).
- Specify the target location (e.g.,
wwwroot/lib/bootstrap/).
-
Using the Files in Views:
<link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.min.css" />
<script src="~/lib/bootstrap/js/bootstrap.bundle.min.js"></script>
Using Webpack for Bundling and Minification
Webpack is a powerful module bundler commonly used in modern web development.
Basic Setup:
-
Initialize NPM:
npm init -y
-
Install Webpack and Plugins:
npm install --save-dev webpack webpack-cli mini-css-extract-plugin css-loader
-
Create webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './wwwroot/js/site.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'wwwroot/dist'),
},
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles.css',
}),
],
mode: 'production', // Enables minification
};
-
Update package.json Scripts:
"scripts": {
"build": "webpack"
}
-
Run Webpack:
npm run build
-
Include the Bundled Files in Views:
<link rel="stylesheet" href="~/dist/styles.css" />
<script src="~/dist/bundle.js"></script>
Explanation:
- Entry Point (
entry): The main JavaScript file.
- Output: The bundled JavaScript and CSS files.
- Loaders: Process CSS files.
- Plugins: Extract CSS into separate files.
- Mode 'production': Enables optimizations like minification.
Benefits of Bundling and Minification
- Reduced HTTP Requests: Fewer files to load improves performance.
- Smaller File Sizes: Minified files load faster.
- Improved Caching: Bundled files can be cached by browsers.
2.2.8. Hands-On Exercises
Let's apply what we've learned with some practical exercises.
Exercise 1: Create a Strongly-Typed View to Display a List of Products
Step 1: Create the Product Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
}
Step 2: Create the ProductController
public class ProductController : Controller
{
// Sample data for demonstration
private static List<Product> _products = new List<Product>
{
new Product { Id=1, Name="Laptop", Price=999.99m, Description="High-performance laptop." },
new Product { Id=2, Name="Smartphone", Price=499.99m, Description="Latest model smartphone." },
new Product { Id=3, Name="Headphones", Price=199.99m, Description="Noise-cancelling headphones." }
};
// GET: Product
public IActionResult Index()
{
return View(_products);
}
}
Step 3: Create the Index View
Location: /Views/Product/Index.cshtml
@model IEnumerable<Product>
@{
ViewData["Title"] = "Product List";
}
<h2>@ViewData["Title"]</h2>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.First().Name)</th>
<th>@Html.DisplayNameFor(model => model.First().Price)</th>
<th>@Html.DisplayNameFor(model => model.First().Description)</th>
</tr>
</thead>
<tbody>
@foreach(var product in Model)
{
<tr>
<td>@product.Name</td>
<td>@product.Price.ToString("C")</td>
<td>@product.Description</td>
</tr>
}
</tbody>
</table>
Explanation:
@model IEnumerable<Product>: Specifies that the view receives a collection of Product.
- Display Names: Uses
DisplayNameFor to dynamically get property names.
- Table Rendering: Iterates over the product list and displays each product's details.
Result:
A web page displaying a table of products with their names, prices, and descriptions.
Exercise 2: Implement a Layout Page with a Header and Footer
Step 1: Create the Layout Page
Location: /Views/Shared/_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewData["Title"] - Product Management</title>
<link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header class="bg-primary text-white p-3">
<div class="container">
<h1>Product Management System</h1>
</div>
</header>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="/">Home</a>
<div class="collapse navbar-collapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="/Product">Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/About">About</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container mt-4">
@RenderBody()
</div>
<footer class="bg-dark text-white text-center p-3 mt-4">
© 2023 Product Management System
</footer>
<script src="~/lib/jquery/jquery.min.js"></script>
<script src="~/lib/bootstrap/js/bootstrap.bundle.min.js"></script>
@RenderSection("Scripts", required: false)
</body>
</html>
Explanation:
- Header: Contains the application title.
- Navigation Bar: Provides links to Home, Products, and About pages.
- Body:
@RenderBody() placeholder for view-specific content.
- Footer: Contains copyright.
- Scripts: Includes jQuery and Bootstrap JS, with a
Scripts section for view-specific scripts.
Step 2: Set the Layout in _ViewStart.cshtml
Location: /Views/_ViewStart.cshtml
@{
Layout = "_Layout";
}
Step 3: Create a Home Controller and View (Optional)
HomeController.cs
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Index.cshtml
Location: /Views/Home/Index.cshtml
@{
ViewData["Title"] = "Home";
}
<h2>Welcome to the Product Management System</h2>
<p>Use the navigation menu to manage products.</p>
Result:
All views using the layout will display the consistent header, navigation bar, and footer, ensuring a uniform look and feel across the application.
Exercise 3: Create Partial Views for Navigation Menu and Sidebar
Step 1: Create Partial Views
-
Navigation Menu Partial
Location: /Views/Shared/_NavMenu.cshtml
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">Product Management</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="/Product">Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/Category">Categories</a>
</li>
</ul>
</div>
</nav>
-
Sidebar Partial
Location: /Views/Shared/_Sidebar.cshtml
<div class="sidebar">
<ul class="list-group">
<li class="list-group-item"><a href="/Product/Create">Add New Product</a></li>
<li class="list-group-item"><a href="/Category/Create">Add New Category</a></li>
<li class="list-group-item"><a href="/Reports">View Reports</a></li>
</ul>
</div>
Step 2: Include Partial Views in the Layout
Modify _Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<!-- Head content -->
</head>
<body>
<header>
@await Html.PartialAsync("_NavMenu")
</header>
<div class="container-fluid">
<div class="row">
<aside class="col-md-3">
@await Html.PartialAsync("_Sidebar")
</aside>
<main class="col-md-9">
@RenderBody()
</main>
</div>
</div>
<footer>
<!-- Footer content -->
</footer>
<!-- Scripts -->
</body>
</html>
Explanation:
- Header: Includes the
_NavMenu partial.
- Sidebar: Placed in a column using Bootstrap grid classes, includes the
_Sidebar partial.
- Main Content: The main area for individual views.
- Partial Rendering: Using
@await Html.PartialAsync() ensures asynchronous rendering.
Step 3: Style the Sidebar (Optional)
Add CSS in site.css:
.sidebar {
background-color: #f8f9fa;
padding: 15px;
height: 100vh;
position: fixed;
}
.main-content {
margin-left: 25%;
padding: 20px;
}
Modify <main> in _Layout.cshtml:
<main class="col-md-9 offset-md-3 main-content">
@RenderBody()
</main>
Result:
The application now has a consistent navigation menu at the top and a sidebar for quick access to common actions like adding products or viewing reports.
Exercise 4: Use Display Templates to Format Product Prices
Step 1: Create a Display Template for decimal Values
Location: /Views/Shared/DisplayTemplates/Price.cshtml
@model decimal?
<span class="text-success">@Model?.ToString("C")</span>
Explanation:
- Formats decimal values as currency.
- Applies a CSS class for styling.
Step 2: Use the Display Template in the View
Modify Index.cshtml
@model IEnumerable<Product>
@{
ViewData["Title"] = "Product List";
}
<h2>@ViewData["Title"]</h2>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.First().Name)</th>
<th>@Html.DisplayNameFor(model => model.First().Price)</th>
<th>@Html.DisplayNameFor(model => model.First().Description)</th>
</tr>
</thead>
<tbody>
@foreach(var product in Model)
{
<tr>
<td>@product.Name</td>
<td>@Html.DisplayFor(modelItem => product.Price)</td>
<td>@product.Description</td>
</tr>
}
</tbody>
</table>
Explanation:
@Html.DisplayFor(modelItem => product.Price): Uses the Price display template to format the price.
Result:
All product prices are displayed in a consistent currency format with the specified styling.
Conclusion
In Module 2.2: Views, we've explored the essential components and techniques for managing views in ASP.NET Core MVC applications. Here's a summary of what we've covered:
-
Razor View Engine:
- Combining C# with HTML using syntax like
@{ }, @, and @* *@.
- Implementing variables, loops, and conditionals within views.
-
Creating and Rendering Views:
- Following naming conventions for views.
- Returning views from controller actions.
- Passing data using
ViewData, ViewBag, and strongly-typed models.
-
Layouts and Sections:
- Creating a consistent layout with
_Layout.cshtml.
- Defining and rendering sections like
Scripts.
-
Partial Views:
- Creating reusable UI components.
- Rendering partial views with data.
-
Display and Editor Templates:
- Customizing the rendering of specific data types.
- Ensuring consistent display and input elements across the application.
-
Strongly-Typed Views:
- Utilizing
@model for type safety and IntelliSense.
- Accessing model properties directly in views.
-
HTML Helpers and Tag Helpers:
- Generating dynamic HTML with both approaches.
- Creating custom Tag Helpers for reusable components.
-
Bundling and Minification:
- Optimizing static files to improve performance.
- Using tools like LibMan and Webpack for managing client-side libraries.
-
Hands-On Exercises:
- Practical implementation of views, layouts, partial views, and templates.
- Enhancing views with consistent styling and functionality.
By mastering these concepts, you'll be well-equipped to create efficient, maintainable, and scalable views in your ASP.NET Core MVC applications. Remember to leverage the built-in features like Tag Helpers and display templates to streamline your development process and maintain consistency across your application.
Feel free to delve deeper into each topic, experiment with the code examples, and apply these practices in your projects to solidify your understanding.