ASP.NET Core by Matthew

Razor View Data

In Razor Pages, you can use the ViewData property to pass data from a Page Model to its corresponding view page, as well as share it with the layout, and any partial views.

ViewData is a dictionary that can contain key-value pairs where each key must be a string. The values can be accessed in the view page using the @ symbol.

A huge benefit of using ViewData comes when working with layout pages. We can easily pass information from each individual view page such as the title, into the layout by storing it in the ViewData dictionary in a view page:

@{ ViewData["Title"] = "Homepage" }

We can then access it in the layout like so: ViewData["Title"]. This way, we don’t need to hardcode certain information on each individual view page.

// Page Model: Index.cshtml.cs
public class IndexModel : PageModel
{
 public void OnGet()
 {
  ViewData["Message"] = "Welcome to my page!";
  ViewData["Date"] = DateTime.Now();
 }
}
 
// View Page: Index.cshtml
@page
@model IndexModel
 
<h1>@ViewData["Message"]</h1>
<h2>Today is: @ViewData["Date"]</h2>

Comments

Leave a Comment

All fields are required. Your email address will not be published.