Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update querystring in C#?

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.

like image 259
developer747 Avatar asked Mar 19 '12 14:03

developer747


People also ask

How do you assign a value to a QueryString request?

So if you're asking how to deal with the value of a query string you just simply access it Request. QueryString["key"]. If you're wanting this 'change' in query string to be considered by the server you just need to effectively reload the page with the new value. So construct the url again page.

How do I pass QueryString?

To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.

What is request QueryString ()?

The value of Request. QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request. QueryString(parameter).

Can we use QueryString with post method?

A POST request can include a query string, however normally it doesn't - a standard HTML form with a POST action will not normally include a query string for example.


2 Answers

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.

like image 108
Ahmad Mageed Avatar answered Oct 14 '22 08:10

Ahmad Mageed


Retrieve the querystring of sortby, then perform string replace on the full Url as follow:

string sUrl = *retrieve the required complete url* string sCurrentValue = Request.QueryString["sortby"]; sUrl = sUrl.Replace("&sortby=" + sCurrentValue, "&sortby=" + newvalue); 

Let me know how it goes :)

Good luck

like image 45
m.othman Avatar answered Oct 14 '22 09:10

m.othman