ASP.NET Razor Pages
A Razor Page is a web page made of two files: the HTML view and a C# class that prepares its data.
The Two Files
| File | Contains |
|---|---|
Pages/Courses.cshtml | HTML and Razor: what the visitor sees |
Pages/Courses.cshtml.cs | The PageModel class: C# logic and data |
Create both with one command:
Example
dotnet new page -n Courses -o Pages --namespace SchoolSite.PagesThe PageModel
Example
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace SchoolSite.Pages;
public class CoursesModel : PageModel
{
public List<string> Courses { get; private set; } = new();
public void OnGet()
{
Courses = new List<string>
{
"Web Development",
"App Development",
"Digital Marketing"
};
}
}OnGet() is a handler. It runs when the browser requests the page with a normal GET request.
The Page
Example
@page
@model SchoolSite.Pages.CoursesModel
@{
ViewData["Title"] = "Our Courses";
}
<h1>Our Courses</h1>
<ul>
@foreach (var c in Model.Courses)
{
<li>@c</li>
}
</ul>Our Courses - Web Development - App Development - Digital Marketing
@pagemakes it a Razor Page@modelconnects it to the PageModelModelgives you the page model's properties
Routing by Folder
The URL of a page comes from its place in the Pages folder:
| File | URL |
|---|---|
Pages/Index.cshtml | / |
Pages/Courses.cshtml | /Courses |
Pages/Admin/Index.cshtml | /Admin |
Pages/Admin/Students.cshtml | /Admin/Students |
URLs are not case sensitive, so /courses and /Courses open the same page.
Route Parameters
You can add a value to the URL with @page "{name}". Here /Course/3 passes the id 3:
Example
@page "{id:int}"
@model SchoolSite.Pages.CourseModel
<h1>Course number @Model.Id</h1>
<p>@Model.Title</p>Example
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace SchoolSite.Pages;
public class CourseModel : PageModel
{
private static readonly Dictionary<int, string> Titles = new()
{
[1] = "Web Development",
[2] = "Graphic Designing",
[3] = "SEO"
};
public int Id { get; private set; }
public string Title { get; private set; } = "";
public IActionResult OnGet(int id)
{
if (!Titles.TryGetValue(id, out var title))
{
return NotFound();
}
Id = id;
Title = title;
return Page();
}
}Course number 3 SEO
{id:int} means the value must be a whole number. /Course/abc will not match. If the id is not in the list, NotFound() sends a 404 page.
Query String Values
Values after ? in the URL can also be handler parameters. For /Search?q=php:
Example
public string Query { get; private set; } = "";
public void OnGet(string? q)
{
Query = q ?? "";
}Links Between Pages
Use the asp-page tag helper instead of writing URLs by hand. ASP.NET builds the correct URL for you:
Example
<a asp-page="/Courses">All courses</a>
<a asp-page="/Course" asp-route-id="2">Graphic Designing</a>The second link becomes /Course/2. If you later move a page, the links still work.
Exercise
Exercise
Which method of a PageModel runs when a page is opened with a normal GET request?
