ASP.NET Core MVC Views

Views are responsible for presenting data to the user. In ASP.NET Core MVC, views are typically implemented using Razor syntax, which allows you to embed C# code within HTML.

Understanding Razor Views

Razor is a templating engine that simplifies the creation of dynamic HTML pages. It uses the .cshtml file extension. Razor files can contain:

  • HTML markup
  • C# code blocks enclosed in @{}
  • Inline C# expressions prefixed with @

Basic Razor Syntax

Here's a simple example of a Razor view:

@model YourAppName.Models.Product

@{
ViewData["Title"] = "Product Details";
}

@Model.Name


Price: @Model.Price.ToString("C")


Description: @Model.Description

View Models

It's common practice to use View Models to pass specific data from the controller to the view. This decouples your view from your domain models and allows for better organization.

Consider a ProductViewModel:

public class ProductViewModel
{
public string Name { get; set; }
public decimal Price { get; set; }
public string DisplayPrice { get; set; } // Formatted price
}

And the corresponding controller action:

public IActionResult Details(int id)
{
var product = _productRepository.GetById(id); // Assuming a repository
var viewModel = new ProductViewModel
{
Name = product.Name,
Price = product.Price,
DisplayPrice = product.Price.ToString("C")
};
return View(viewModel);
}

Layout Pages

Layout pages define the overall structure of your application, such as headers, footers, and navigation. They reduce code duplication.

A typical layout file (_Layout.cshtml) might look like this:





@ViewData["Title"] - MyApp


@RenderBody()
@await RenderSectionAsync("Scripts", required: false)

To use a layout, a view can specify its layout using the Layout property in a Razor code block:

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

If a view doesn't specify a layout, and the application has a default layout specified in Startup.cs or Program.cs, that default layout will be used.

Partial Views

Partial views are reusable view components that can be rendered within other views. They are useful for breaking down complex views into smaller, manageable parts.

To render a partial view:

@await Html.PartialAsync("_ContactInfoPartial", Model.ContactInfo)

Or:

The _ContactInfoPartial.cshtml might contain:

@model YourAppName.Models.ContactInfo

Contact Details

Email: @Model.Email

Phone: @Model.Phone

Key Concept: Razor syntax allows for clean separation of concerns by embedding dynamic data and logic directly within HTML structures, making UI development intuitive.

View Components

View Components are similar to partial views but are more powerful. They can have their own C# code (a component class) and can be invoked directly from controllers or Razor views.

Example Scenario: Displaying a shopping cart summary.

Example: Rendering a Partial View for Navigation

Let's say you have a navigation menu that needs to be consistent across multiple pages.

Controller Action:
public IActionResult Index()
{
var menuItems = new List { "Home", "Products", "About" };
return View(menuItems);
}
View (Index.cshtml):
@model List

@{
ViewData["Title"] = "Home Page";
}

Welcome!


Here is our navigation:


@await Html.PartialAsync("_NavigationPartial", Model)
Partial View (_NavigationPartial.cshtml):
@model List
CSS for Styling (site.css):
.contact-info h4 { color: #0078d4; margin-bottom: 10px; } nav ul { list-style: none; padding: 0; } nav ul li { display: inline-block; margin-right: 20px; } nav ul li a { text-decoration: none; color: #333; }

Working with Tag Helpers

Tag Helpers enable server-side code to participate in modifying HTML elements and attributes in Razor files. They provide a more HTML-friendly way to express ASP.NET Core MVC server logic.

For example, the <a> tag helper:

<a asp-controller="Products" asp-action="Index">View Products</a>

This generates an HTML link like:

<a href="/Products">View Products</a>

Another example using a form:

<form asp-controller="Account" asp-action="Login" method="post">
<!-- Input fields here -->
<button type="submit">Login</button>
</form>
Tip: Always use Tag Helpers for generating URLs and form elements to ensure they are robust and handle routing changes gracefully.