Rustam Salakhutdinov
Rustam Salakhutdinov

Reputation: 804

Set query parameter based on current URL

I am working on a standard paging component for my project. All controllers with paging are waiting for PageIndex parameter in URL.

So I want to generate URL based on the current URL except for the PageIndex parameter.

For example, I have filters for my internet store like Manufacturer and MaxPrice. A user opens the mystore.com/products?manufacturer=Apple&MaxPrice=999 link.

Then he wants to go to the 3 pages. So the 3-page link in my paging should have the mystore.com/products?manufacturer=Apple&MaxPrice=999&PageIndex=3 link.

enter image description here

So needed MVC function should:

  1. Persists all existing params like MaxPrice and manufacturer
  2. Replace only PageIndex param
  3. don't use any hardcoded controller and action values (like controller = 'Products', Action = 'Index')

I try to use this code:

<a class="page-link" href="@Url.RouteUrl(new { PageIndex = page })">
    @page
</a>

It works fine except the 2 rule - it doesn't persist other arguments. So if user click on this link he goes to mystore.com/products?PageIndex=3

Upvotes: 1

Views: 2409

Answers (2)

George Viennas
George Viennas

Reputation: 29

You can use these to get the current url

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TEST/Default.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TEST/Default.aspx

And then you can add the page index like this and redirect to that url

url = url+"&PageIndex=3";

Recommended

Or you can get the url parameters with

@Url.RequestContext.RouteData.Values["manufacturer"]
@Url.RequestContext.RouteData.Values["MaxPrice"]

And use those values to build the new URL inside the View

Upvotes: 0

Mohammad Ghanem
Mohammad Ghanem

Reputation: 726

I suggest to build the url dynamically by getting currentUrl with query strings "Request.Url.AbsoluteUri" then remove the pageIndex from url if exists , then add page index again.

hint : url must be defined as variable in your razor to make the things easier

To remove query string you can use regex

string queryString = "Default.aspx?Agent=10&Language=2"; //Request.QueryString.ToString();
string parameterToRemove="Language";   //parameter which we want to remove
string regex=string.Format("(&{0}=[^&\s]+|{0}=[^&\s]+&?)",parameterToRemove);
string finalQS = Regex.Replace(queryString, regex, "");

Upvotes: 1

Related Questions