State Management Part 5 - The Query String

Name: *
My email: *
Recipient email: *
Message: *
Fields marked as bold are compulsory.
You haven't filled in compulsory values. The email is not correct

Query string is one of the easiest ways to transfer info when moving from one page to another. The information is stored right in the url. This way the page you are viewing can be easily "copied" and viewed later on, or sent to another user. However, as it stands in plain view, you shouldn't keep sensitive data within the query string.

 

What is the Query String

So far we've come across ways that store information within the server or the client. The query string belongs to none as it stores information within the query string. The form of a url using the query string would look like
url?key1=value1&key2=value2...
 
What does this mean? url stands for the requested page url. Url must be followed by a question mark '?'. After that comes the key being the name of the value we want to store and its value.
 
Should we want to store more than one value in the query string we would have to use an ampersand '&' between the distinct values.
 
For example, when you entered the blog, the url would be http://dotnethints.com/blog.aspx. Just a plain url. This would point to this page.
 
querystring
 
Now, click on a blog article and you will be redirected to an inner page http://dotnethints.com/blog.aspx?id=21. Take a look at the url. Even though the aspx page is the same as before, the content we see is different. 
 
 
query string 2
 
 
That is because the source code examines the query string. It is searching for a parameter named id and it knows that this value represents the id of the article it is supposed to show. From that on the source code takes control and does what is necessary so that you can read the article right now.
 
If we needed more than one parameter we would have to use an ampersand. For example, search for dotnet hints in Google you get the following url
https://www.google.gr/search?q=dotnet+hints&oq=dotnet+hints&aqs=chrome.0.57j60l4j0.2789&sugexp=chrome,mod=0&sourceid=chrome&ie=UTF-8
 
Notice there is the question mark ?, followed by the parameter q=dotnet+hints, followed by an ampersand '&, followed by other parameters oq=dotnet+hints and so on. 
 
Now, the best thing about the query string is that everyone can use this url. Even if you do not search Google you can still see the results I did by clicking the previous link. There is no info on the server needed and no info in your browser either. Most websites wish to use the query string so that a person can send the url to his friends or add a bookmark in his browser.
 

How to use the query string

It is quite easy to use the query string.
 
For example you can use Response.Redirect to move into the new page like this
Response.Redirect("NewPage.aspx?kew=" + value);
 
It is a good idea to use Server.UrlEncode before inserting the value in the url.
 
Since we store the value within the url it would be difficult to handle a value such as "Hello World" as it contains a space character ' '. UrlEncode transforms such characters int url compatible from. For example ' ' will become '+' and '&' will become %26.
 
There is also the Server.UrlDecode method, however it useless ASP.Net automatically decodes the values when using Request.QueryString[key] way of obtaining values.
 
Values in ASP.NET are stored in dictionary-like mode, so it is quite easy to retrieve them using
string queryStringValue = Request.QueryString[key];
 
If the requested key does not exist, the string will be null.
 

Example

Since we' ve talked a lot about the query string let's create an example to see how it works using C#. It is similar to the one we had in the previous sessions where you choose your holiday destination. The user will first pick the country he wishes, then he will pick the city and, finally, he will get a message informing him of his destination.
 
This is the CountriesQueryString.aspx page
 
    Select the country you wish to visit:
    <br />
 
    <asp:DropDownList runat="server" ID="CountriesListID"  AutoPostBack="true"  OnSelectedIndexChanged="CountrySelected">
    <asp:ListItem Text="" Value="0" />
    <asp:ListItem Text="Italy" Value="1" />
    <asp:ListItem Text="France" Value="2" />
    <asp:ListItem Text="Greece" Value="3" />
    <asp:ListItem Text="United Kingdom" Value="4" />
    </asp:DropDownList>
 
 
and this is the code behind part
 
   protected void CountrySelected(object sender, EventArgs e)
    {
        //Save value to the query string  and redirect to next page
        Response.Redirect("CitiesQueryString.aspx?country=" + Server.UrlEncode(CountriesListID.SelectedItem.Text));
    }
 
query string example 1
 
When we select a country we will be redirected to the second page. Pay attention to the way we create the url. The name of the page and the key are static and we insert the value through the drop down list. You may notice that we use Server.UrlEncode before inserting the value in the url.
 
This will be our new url: CitiesQueryString.aspx?country=France
 
Now it's time to move to the next page CitiesQueryString.aspx
 
    Select the city you wish to visit:
    <br />
    <asp:DropDownList runat="server" ID="CitiesListID" AutoPostBack="true" OnSelectedIndexChanged="CitySelected">
        <asp:ListItem Text="" Value=""/>
    </asp:DropDownList>
 
and the code behind part
 
 
protected void Page_Load(object sender, EventArgs e)
    {
        //Checking for postback is needed so that DropDownList controls are filled with ListItems only the first time they are requested 
        if (!IsPostBack)
            {
                // Page gets value that was inserted in the query string in the CountriesQueryString.aspx
                // Shows cities available to selected country
                string countryValue =  Request.QueryString["country"];
                if(countryValue == "Italy")
                {
                    CitiesListID.Items.Add(new ListItem("Rome", "1_1"));
                    CitiesListID.Items.Add(new ListItem("Florence", "1_2"));
                }
                else if(countryValue == "France")
                {
                    CitiesListID.Items.Add(new ListItem("Paris", "2_1"));
                    CitiesListID.Items.Add(new ListItem("Cannes", "2_2"));
                }
                else if (countryValue == "Greece")
                {
                    CitiesListID.Items.Add(new ListItem("Athens", "3_1"));
                    CitiesListID.Items.Add(new ListItem("Mykonos", "3_2"));
                }
                else if (countryValue == "United Kingdom")
                {
                    CitiesListID.Items.Add(new ListItem("London", "4_1"));
                    CitiesListID.Items.Add(new ListItem("Birmingham", "4_2"));
                }
            }
    }
 
All we do is get the value stored in the query string and use it to get the availabe cities.
 
query string example 2
 
When we select a city, the following code will run where we will create a new url. This will store two values, countryid and cityid.
 
    protected void CitySelected(object sender, EventArgs e)
    {
        //Save both values in the query string and redirect to final page
        string countryValue = Request.QueryString["country"];
        string cityValue = CitiesListID.SelectedItem.Text;
        Response.Redirect("CheckOut.aspx?country=" + Server.UrlEncode(countryValue) + "&city=" + Server.UrlEncode(cityValue));
    }
 
Eventually we reach the final page. We will get the values from the url, like the way we did in the previous page and show them in our page.
Our url is CheckOut.aspx?country=France&city=Paris
 
 
    Congratulations, next week you are flying to 
    <asp:Literal runat="server" ID="CheckOutLitID" />
 
and the code behind part
 
 
protected void Page_Load(object sender, EventArgs e)
    {
        string location = "";
 
        //Get values from the query string
        if (Request.QueryString["country"] != null)
            location += Request.QueryString["country"]
 
        if (Request.QueryString["city"]!= null)
            location += " , " +  Request.QueryString["city"];
 
        CheckOutLitID.Text = location;
 
    }
 
query string example 3

More about the query string

The query string can be very effective when used properly. It will not slow down the server or increase the response time, as its contain can only be of limited length (1-2 KB). This way it can be perfect to show user around catalogs and categories of products.
 
However it is not always the perfect solution. As mentioned, the url stands in plain view. Storing a blog article ID in the url is ok, but storing user info like usernames or IDs is a really bad idea. Supposing the only way a user would seem to be logged would be through a query string parameter userid, for example  http://dotnethints.com/blog.aspx?userid=221. If he sent that url to friend, then his friend would be instantly logged in as the person. 
 
Since the query string is stored in the url and the url can be clicked numerous times, try not to create query strings that can end up to unexpected results if clicked more than once, eg web banking transactions.
 
The query string can only store values in the form of string. As a result it works fine with string and numeric values but can be difficult or impossible to handle with more complex types.
 
A query string, being part of a url, has restricted length. So, storing a full text within the query string is no good idea either.
 
 

Conclusion

The query string can be a very effective tool when used properly. It stores small values in the url and can be easily copied, thus 'storing' the page's content. However, it should not be used to store sensitive data or complex data types.

Back to BlogPreviousNext

Comments



    Leave a comment
    Name: