Using Query Strings in Asp.Net

Leave a Comment

Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant.

Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.

Let’s assume that we have a GridView with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be a ideal use of the Query String to include the product ID in the Query String of the link to the product details page(for example, productdetails.aspx?productid=4).

When product details page is being requested, the product information can be obtained by using the following codes :

Query strings is used to Pass the values or information from one page to another page.

Syntax :
Request.QueryString(variable)[(index)|.Count]

variable : Specifies the name of the variable in the http query string to retrieve.
index : An optional parameter that enables you to retrieve one of multiple values for variable. It can be any integer value in the range 1 to Request.QueryString(variable).Count.

Example :

Page1.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
    {
        int ID = 10;
        string name = "Ajay Patel";
        Response.Redirect("Default2.aspx?id=" + ID + "&name=" + name);
    }

Page2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString[0] != null && Request.QueryString[1] != null)
        {
            /* string id = Request.QueryString[0].ToString();
            string name = Request.QueryString[1].ToString();
            */
            string id = Request.QueryString["id"].ToString();
            string name = Request.QueryString["name"].ToString();
            Response.Write(id + " " + name);
        }
    }
Download Source Code

0 comments:

Post a Comment