C# – How to update querystring in C#

asp.netcquery-string

Somewhere in the url there is a &sortBy=6 . How do I update this to &sortBy=4 or &sortBy=2 on a button click? Do I need to write custom string functions to create the correct redirect url?

If I just need to append a query string variable I would do

string completeUrl = HttpContext.Current.Request.Url.AbsoluteUri + "&" + ...
Response.Redirect(completeUrl);

But what I want to do is modify an existing querystring variable.

Best Answer

To modify an existing QueryString value use this approach:

var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("sortBy", "4");
string url = Request.Url.AbsolutePath;
Response.Redirect(url + "?" + nameValues); // ToString() is called implicitly

I go into more detail in another response.