CodexBloom - Programming Q&A Platform

ASP.NET Core 6 Razor Pages: Unable to Pass Additional Query Parameters in PageModel

👀 Views: 77 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-22
asp.net-core razor-pages mvc query-parameters csharp

I'm working through a tutorial and I'm stuck on something that should probably be simple. I'm testing a new approach and I keep running into Hey everyone, I'm running into an issue that's driving me crazy....... I'm currently working on a Razor Pages application using ASP.NET Core 6, and I've encountered an issue with passing additional query parameters to my PageModel. I have a page that lists products, and I'm trying to implement a filtering feature where users can select product categories. However, when I try to pass the selected category as a query parameter, it seems that the routing does not capture it correctly, and I end up with a default value instead. Here's the setup I have in my Razor Page: ```csharp public class ProductsModel : PageModel { public List<Product> Products { get; set; } public string SelectedCategory { get; set; } public void OnGet(string category) { SelectedCategory = category; Products = GetFilteredProducts(category); } private List<Product> GetFilteredProducts(string category) { // Assume this method fetches products based on the category. return ProductRepository.GetProductsByCategory(category); } } ``` In my Razor view, I have a dropdown that allows users to select a category, and on change, I redirect to the same page with the selected category: ```html <select id="categorySelect" onchange="location = this.value"> <option value="/Products?category=Electronics">Electronics</option> <option value="/Products?category=Clothing">Clothing</option> <option value="/Products?category=Home">Home</option> </select> ``` However, when I select a category from the dropdown, the `SelectedCategory` property in my PageModel is always null or gets a default value. I have checked the generated URLs in the browser, and they seem correct (e.g., `/Products?category=Electronics`). I also confirmed that the `OnGet` method is triggered because I can see the page reloads, but `category` remains null. I've tried changing the parameter name to match the property name and ensuring that the routes are correctly configured in `Startup.cs`, but nothing seems to help. Is there something I'm missing in terms of MVC routing or Razor Page conventions? Any help or insights would be greatly appreciated! For context: I'm using Csharp on Windows. What's the best practice here? This is for a REST API running on Ubuntu 20.04. Any pointers in the right direction? This is my first time working with Csharp stable. I recently upgraded to Csharp stable. Is there a simpler solution I'm overlooking?