Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor Pages: Passing query parameters in a link

Tags:

razor-pages

I tried in the razor page:

<div>
    @foreach (var cat in Model.Categories)
     {
        
        <a asp-page="/[email protected]">@cat.Name</a>
     }
    
</div>

And in the cs file:

public void OnGet()
        {
            CurPage = 1;
            CatId = -1;
            Search = "";
            HasCarousel = false;
            Title = "All Products";
            var queryParams = Request.Query;
            foreach(var qp in queryParams)
            {
                if (qp.Key == "curPage") CurPage = int.Parse(qp.Value);
                if (qp.Key == "catId") CatId = int.Parse(qp.Value);
                if (qp.Key == "search") Search = qp.Value;
                if (qp.Key == "hasCarousel") HasCarousel = bool.Parse(qp.Value);
            }

But when i click the link no query parameter is added to the address and the Request.Query is empty. What am I doing wrong? Or what is the right way to pass the query parameters to a razor page via a link?

like image 322
user1238784 Avatar asked Oct 22 '25 07:10

user1238784


1 Answers

To add query parameters to your link you can use asp-route- in your a tag. In your case it would look like

<a asp-page="Index" asp-route-catId="@cat.Id">@cat.Name</a>

You're also making receiving the query parameters in your OnGet() harder than it has to be. You can add parameters to your method signature like

OnGet(int catId)

and they will be passed in by the query parameters.

like image 113
Tony Pacheco Avatar answered Oct 25 '25 05:10

Tony Pacheco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!