18 November 2026

Razor Pages Routing: Route IDs and Query Strings for Beginners

  Asp.Net CS By Example       18 November 2026

A URL can carry small pieces of information to a Razor Page. Use a route parameter for the identity of a page, such as a student ID. Use a query string for an optional view choice, such as which tab to show.

Example URL
/Students/Details/2?tab=grades
2 is the route ID. grades is the query value named tab.

1. Add a page with a route ID

In a project created with dotnet new webapp, create Pages/Students/Details.cshtml:

@page "{id:int}"
@model StudentSite.Pages.Students.DetailsModel

<h1>Student details</h1>
<p>Name: @Model.StudentName</p>
<p>Selected tab: @Model.SelectedTab</p>

The file path gives the page its basic URL, /Students/Details. The route template {id:int} adds a required integer segment, such as /Students/Details/2. A missing or non-integer ID does not match this route.

2. Read both values in OnGet

Create Pages/Students/Details.cshtml.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace StudentSite.Pages.Students;

public class DetailsModel : PageModel
{
    public string StudentName { get; private set; } = string.Empty;
    public string SelectedTab { get; private set; } = "profile";

    public IActionResult OnGet(int id, string? tab)
    {
        var students = new Dictionary<int, string>
        {
            [1] = "Asha",
            [2] = "Ravi"
        };

        if (!students.TryGetValue(id, out var name))
            return NotFound();

        StudentName = name;
        SelectedTab = tab == "grades" ? "grades" : "profile";
        return Page();
    }
}

ASP.NET Core binds id from the route and tab from the query string to the handler parameters. The page checks that the ID exists. It also restricts the tab to two expected values rather than trusting any text in the URL.

3. Try three URLs

  1. /Students/Details/1 shows Asha and the default profile tab.
  2. /Students/Details/2?tab=grades shows Ravi and the grades tab.
  3. /Students/Details/99 returns 404 because student 99 is not in the example data.

4. Generate a link

In another Razor page, use tag helpers to make a link without joining strings by hand:

<a asp-page="/Students/Details"
   asp-route-id="2"
   asp-route-tab="grades">Ravi's grades</a>

The route ID becomes part of the path; the extra tab value becomes a query parameter. URL generation handles encoding for you.

Remember: URL values are input from the browser. Validate them, and never use a route ID alone as proof that a person is allowed to view a record.

Further reading: Microsoft Learn: Razor Pages routing and model binding.

logoblog

Thanks for reading Razor Pages Routing: Route IDs and Query Strings for Beginners

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.