'ASP.NET Core MVC - Add additional route parameters to existing URL without losing existing query params

I'm trying to make offset-based pagination in my project, but I have encountered a problem. So I have a link to redirect users to a specific page based on page number (i - in this case):

<a class="page-link" asp-route-pageNumber="@i"> @i </a>

But the problem is that if I want first to filter my table e.g where for example userStatus is ACTIVE (1 in my case) and I have assigned a tableSize (to show only 5 rows) my URL would look like this:

localhost:8080/users/?tableSize=5&userStatus=3

Now if I want to go to the second page which is the same as the anchor link above the URL gets overridden and my userStatus and tableSize query parameters are gone and only pageNumber is there!

localhost:8080/users/?pageNumber=2

How can I make the link to only add the pageNumber to the existing URL as a query parameter and increment its value when I click another page number link and be like this:

localhost:8080/users/?tableSize=5&userStatus=3&pageNumber=2

I wouldn't like to use jQuery or JavaScript but if that is the only or better way feel free to share it!

I tried to use JavaScript to fire an on-click event when I click on a specific page number but that is not working properly, because every time I am clicking the link the function is adding another pageNumber parameter to the URL, and if I check the URL first if pageNumber exists then the value of query param would be a mess to replace it.



Solution 1:[1]

If you mean your current url is localhost:8080/xxx/?tableSize=5&userStatus=3,and you want to add the value of tableSize and userStatus to <a class="page-link" asp-route-pageNumber="@i"> @i </a>.You can try the following code:

@{
    string tableSize= Context.Request.Query["tableSize"].ToString();
    string userStatus= Context.Request.Query["userStatus"].ToString();
}
<a class="page-link" asp-route-pageNumber="@i" asp-route-tableSize=@tableSize asp-route-userStatus=@userStatus> @i </a>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yiyi You