Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Query string parameters in asp.net core razor pages

Suggested Videos
Part 6 - Registering services in razor pages project | Text | Slides
Part 7 - List razor page | Text | Slides
Part 8 - Routing in asp.net core razor pages | Text | Slides

In this video we will discuss query string parameters in asp.net core razor pages.

Consider the following razor page that displays the list of employees. When the View button is clicked, the ID of the employee must be passed to the Details.cshtml razor page. The details page then retrieves and displays the respective employee details.


razor pages routing parameters


<a asp-page="/Employees/Details" asp-route-ID="@employee.Id"
   class="btn btn-primary m-1">View</a>
  • asp-page tag helper points to the Details razor page
  • asp-route-ID tag helper passes the Employee ID to the details razor page
  • You can include as many asp-route-* tag helpers as you want. For example, in addition to employee id, if you want to pass employee name, you may use another asp-route-name tag helper.
By default employee ID is passed as a query string parameter to the Details page

https://localhost:44383/Employees/Details?ID=1

Model-binding in asp.net core automatically maps the ID query string parameter value to the ID parameter on the OnGet() method in the PageModel class.

Details.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPagesTutorial.Models;
using RazorPagesTutorial.Services;

namespace RazorPagesTutorial.Pages.Employees
{
    public class DetailsModel : PageModel
    {
        private readonly IEmployeeRepository employeeRepository;

        public DetailsModel(IEmployeeRepository employeeRepository)
        {
            this.employeeRepository = employeeRepository;
        }

        public Employee Employee { get; private set; }

        // Model-binding automatically maps the query string id
        // value to the id parameter on this OnGet() method
        public void OnGet(int id)
        {
            Employee = employeeRepository.GetEmployee(id);
        }
    }
}

Details.cshtml

@page
@model RazorPagesTutorial.Pages.Employees.DetailsModel
@{
    ViewData["Title"] = "Details";
    var photoPath = "~/Images/" + (Model.Employee.PhotoPath ?? "noimage.jpg");
}

<div class="row justify-content-center m-3">
    <div class="col-sm-8">
        <div class="card">
            <div class="card-header">
                <h1>@Model.Employee.Name</h1>
            </div>

            <div class="card-body text-center">
                <img class="card-img-top" src="@photoPath" asp-append-version="true" />

                <h4>Employee ID : @Model.Employee.Id</h4>
                <h4>Email : @Model.Employee.Email</h4>
                <h4>Department : @Model.Employee.Department</h4>

            </div>
            <div class="card-footer text-center">
                <a asp-page="index"
                   class="btn btn-primary">Back</a>
                <a href="#" class="btn btn-primary">Edit</a>
                <a href="#" class="btn btn-danger">Delete</a>
            </div>
        </div>
    </div>
</div>

IEmployeeRepository.cs

using RazorPagesTutorial.Models;
using System.Collections.Generic;

namespace RazorPagesTutorial.Services
{
    public interface IEmployeeRepository
    {
        IEnumerable<Employee> GetAllEmployees();
        Employee GetEmployee(int id);
    }
}

MockEmployeeRepository.cs

using RazorPagesTutorial.Models;
using System.Collections.Generic;
using System.Linq;

namespace RazorPagesTutorial.Services
{
    public class MockEmployeeRepository : IEmployeeRepository
    {
        private List<Employee> _employeeList;

        public MockEmployeeRepository()
        {
            _employeeList = new List<Employee>()
            {
                new Employee() { Id = 1, Name = "Mary", Department = Dept.HR,
                    Email = "mary@pragimtech.com", PhotoPath="mary.png" },
                new Employee() { Id = 2, Name = "John", Department = Dept.IT,
                    Email = "john@pragimtech.com", PhotoPath="john.png" },
                new Employee() { Id = 3, Name = "Sara", Department = Dept.IT,
                    Email = "sara@pragimtech.com", PhotoPath="sara.png" },
                new Employee() { Id = 4, Name = "David", Department = Dept.Payroll,
                    Email = "david@pragimtech.com" },
            };
        }

        public IEnumerable<Employee> GetAllEmployees()
        {
            return _employeeList;
        }

        public Employee GetEmployee(int id)
        {
            return _employeeList.FirstOrDefault(e => e.Id == id);
        }
    }
}

ASP.NET Core RouteOptions

The RouteOptions object allow us to customise query string parameters. For example, if you want the query strings in the URL in lower case, set LowercaseQueryStrings property to true. For this to work LowercaseUrls property must also be set to true. The default value for both these properties is false.

As the name implies, AppendTrailingSlash property appends a trailing slash to the generated URLs.


services.Configure<RouteOptions>(options =>
{
    options.LowercaseUrls = true;
    options.LowercaseQueryStrings = true;
    options.AppendTrailingSlash = true;
});

asp.net core razor pages tutorial

3 comments:

  1. Hello sir,
    How can i do OnGet(studentId) and OnGet(studentCourseById) on the same page? so, studentInformation at the top and StudentCourses on the bottom of the same page. Can I use different names for OnGet()? Thanks

    ReplyDelete
  2. Hi there I saw the video I read this article very carefully, I implented your code to my project and in MockEmployeeRepository I always get this error when I build 'MockEmployeeRepository._employeeList' is never assigned to, and will always have its default value null I am using asp.net 5.0 mvc need some help please

    ReplyDelete
  3. Ok I got one problem solved I did put this in the startup properly

    services.AddSingleton();

    i put services.AddSingleton();

    but now I have another problem when I go to https://www.dbtweb.com/web/portfoliodetails?ID=3

    this error come up

    Object reference not set to an instance of an object.

    on line 15 I put this demo/images/@Model.portentry.SmallImage

    Once again I need help please, thanks

    ReplyDelete

It would be great if you can help share these free resources