Passing multiple variables or parameters using a QueryString in Asp.Net

← PrevNext →

Sometimes we need to pass data between web pages to share information in the form of variables or parameters. We can do this by using a “QueryString” of “Request” property in Asp.Net. QueryString is a part of the URL shown in the Address bar of a browser.

A Typical URL

https://www.encodedna.com/

URL using a QueryString

www yourwebsite com?search=some_search_value

In the above example, I am passing a single parameter (highlighted in bold) as a value for our QueryString. The “?” sign (Question Mark) in the QueryString separates the URL and the value. The elements after the “?” are the Field and Value respectively. The value can be a string, numeric or both.

Passing Multiple Parameters for QueryString

To pass multiple parameters, we will use “&” symbol to separate the other field and value combinations.

https://www yourwebsite com /content/ocncontent?userid=43&contentid=9

On button click (from code behind), redirect to another page with two QueryString parameters.

Response.Redirect("https://www yourwebsite com /content/ocncontent?userid=43&contentid=9")

Now this example has two parameters or variables. The first is the userid=43 and second is the contentid=9 respectively. You may add more parameters as per your requirement.

The page which is called can read the QueryString fields and values using the Request property in Asp.Net. There are 2 very common ways of reading the fields and values.

Read by Variables

Response.Write(Request.QueryString(“userid”))

Response.Write(Request.QueryString(“contentid”))

Read by Indexes

Response.Write(Request.QueryString(0))

Response.Write(Request.QueryString(1))

Read All QueryStrings

If you want to read all the parameters in the QueryString, then we many use the below code. Add the code in the form load event.

C#
string str = "";

foreach (string str_loopVariable in Request.QueryString) {
    str = str_loopVariable;
    Response.Write(Strings.UCase(str) + " - " + (Request.QueryString(str)));
    Response.Write(Constants.vbCrLf);
}
Vb.Net
Dim str As String = ""

For Each str In Request.QueryString
    Response.Write(UCase(str) & " - " & (Request.QueryString(str)))
    Response.Write(vbCrLf)
Next

That's it. Thanks for reading.

← PreviousNext →