Add, remove or modify the query string value in URL in ASP.NET

In some cases we need searching records through different filter parameters, and the same should reflects in our URL by query string parameters. Here I have mentioned the native .net approach to add, remove or modify the query string parameters in server side code.
1. In first step, we need to get the Current URL text
 string url = HttpContext.Current.Request.Url.AbsoluteUri;
2. Then splitting the query string part from URL.
 string[] separateURL = url.Split('?');
Here I have tried to split the string into a string array,which can be done by other ways also.But here main aim is to extract the query string part of the URL.
3. In ASP.NET there is HttpUtility class inside System.web namespace, which helps to parse the query string parameters into a name-value collection object.
 NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(separateURL[1]) ; // Pass the Querystring part.
Now we can modify the value such as
 queryString["member"] = txtMemberSearch.Text;
 queryString["phone"] = txtPhoneNumber.Text;
Also we can Remove some query string part .
We can add another query string value if it does not exists before as given below.
 queryString["priority"] = ddlPriority.SelectedItem.Text; //selected item from dropdown list.
4. After resetting all parameters of our need, we need to convert that name-value collection object into string and append to the query.
 url = separateURL[0] + "?" + queryString.ToString();
Now, you can use this new URL to navigate with all desired parameters.
Ebook Download
View all
View all