This tutorial will demonstrate how to use query strings with ASP.NET 4.0 and C#.

What is a QueryString?

A query string is a value specified in an HTTP query that can be accessed easily within ASP.NET. The query string is appended at the end of the URL following the question mark(‘?’) character. Multiple query strings can be specified in the URL by separating them by either an ampersand(‘&’) or a semicolon(‘;’). The following is an example of the query string with a field name of ‘id’ and a value of ‘1’: http://www.mywebsite.com/default.aspx?id=1. Query strings can be used for many different reasons, one common use is to display different data on the same page based on the query string. For example, if I had an online store and wanted a page to display an inidividual item from my database on the page, we could use a query string. This would work by passing something such as the item’s id in the database as a query string to the page, and then displaying data from the database based on the value of the query string.

Using QueryStrings

You can access the query strings of a given page in either the front end or back end of the code. To demonstrate how to do this, we will create a simple web site. First, create a new ASP.NET Empty Web Site and then:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx.cs up for editing.

Add the following code to the Page_Load event method:

This code will display two values that are of interest to us. First, the value of the query string named ‘id’ and then the total number of query string parameters that are found in our URL.

To access the query string from the front end, add in the following to the Default.aspx page:

This will output the value of the ‘id’ query string to the page.

Testing

To test this out, simply load up the page. Notice that the number of parameters is currently zero. If we append the following to the end of the URL ‘?id=1&othervalue=3’ and reload the page, you will notice that the number ‘1’ which is the value of our ‘id’ query string is being displayed. Also, you will notice the number of query strings changed to two. You can pass pretty much any simple data type through a query string, but only as long as the data is short. For example, you would not want to pass a string that is 300 characters long through a query string because the user will see that reflected in the URL of the page. Furthermore, because the data is visible you do not want to pass any sort of sensitive data through the query string such as a password.
Download Source Files