PageModel and Routing
Beginner
20 min read
Lesson 2 of 8
PageModel
The PageModel is the code-behind file for a Razor Page.
// Pages/Products/Index.cshtml.cs
public class IndexModel : PageModel
{
private readonly ApplicationDbContext _context;
public List<Product> Products { get; set; }
public IndexModel(ApplicationDbContext context)
{
_context = context;
}
public async Task OnGetAsync()
{
Products = await _context.Products.ToListAsync();
}
}
Routing
Default Routing
// Pages/Products.cshtml → /Products
// Pages/Products/Index.cshtml → /Products
// Pages/Products/Details.cshtml → /Products/Details
Custom Routing
// Pages/Products/Details.cshtml
@page "{id:int}"
@model DetailsModel
// URL: /Products/Details/5
Route Parameters
// Pages/Products/Details.cshtml
@page "{id:int?}"
public class DetailsModel : PageModel
{
public int? Id { get; set; }
public void OnGet(int? id)
{
Id = id;
}
}
Route Constraints
// Pages/Products/Details.cshtml
@page "{id:int:min(1)}" // Must be positive integer
@page "{slug:alpha}" // Must be alphabetic
@page "{id:guid}" // Must be GUID
Key Takeaway
PageModel contains the logic for a page, and routing determines how URLs map to pages.