Add Parameters to Query String in C# - Programming Tips

When working with web development in C#, it's common to need to add parameters to the query string in order to pass data between pages. This can be achieved through the use of the HttpUtility class and its method, "ParseQueryString".

To start, you'll need to define the parameters you want to add in a dictionary. For example, let's say you want to add a "name" and "age" parameter to the query string. You would define the dictionary like this:

Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("name", "John");
parameters.Add("age", "30");

Once you have your dictionary, you can use the HttpUtility class to parse it into a query string like so:

string queryString = HttpUtility.ParseQueryString(string.Empty);
foreach (KeyValuePair<string, string> parameter in parameters)
    queryString += "&" + parameter.Key + "=" + HttpUtility.UrlEncode(parameter.Value);

In this code, we first initialize an empty query string using the ParseQueryString method. We then loop through each parameter in our dictionary and append it to the query string using the "&" symbol as a separator. We also use the UrlEncode method to ensure any special characters in the parameter values are properly encoded.

Finally, we can append the generated query string to the URL of the page we want to navigate to. For example, if we wanted to navigate to a page called "profile.aspx", we would do so like this:

Response.Redirect("profile.aspx?" + queryString);

With this code, we can easily add parameters to the query string and pass data between pages in our C# web applications.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information