Bookmark this blog

How to pass query string in asp.net? Advantage and disadvantages of using query string.

Introduction

Often you need to pass variable content between your html pages or aspx webforms in context of Asp.Net. For example in first page you collect information about your client, her name and last name and use this information in your second page.

For passing variables content between pages ASP.NET gives us several choices. One choice is using QueryString property of Request Object. When surfing internet you should have seen weird internet address such as one below.

http://www.localhost.com/Webform2.aspx?name=manas&lastName=sahu

This html addresses use QueryString property to pass values between pages. In this address you send 3 type of information.

  1. Webform2.aspx: this is the page your browser will go.
  2. Name: name variable which is set to manas
  3. lastName: lastName variable which is set to sahu

As you have guessed ? starts your QueryString, and & is used between variables. Building such a query string in Asp.Net is very easy. Our first form will have 2 textboxes and one submit button.

Put this code to your submit button event handler.

private void btnSubmit_Click(object sender, System.EventArgs e)

{

    Response.Redirect("Webform2.aspx?Name=" +

    this.txtName.Text + "&LastName=" +

    this.txtLastName.Text);

}

Our first code part builds a query string for your application and send contents of your textboxes to second page. Now how to retrieve this values from second page. Put this code to second page page_load.

private void Page_Load(object sender, System.EventArgs e)

{

    this.txtBox1.Text = Request.QueryString["Name"];

    this.txtBox2.Text = Request.QueryString["LastName"];

}

Request.QueryString is overloaded with a second way. You can also retrieve this values using their position in the querystring. There is a little trick here. If your QueryString is not properly built Asp.Net will give error.

private void Page_Load(object sender,

 

System.EventArgs e)

{

    this.txtBox1.Text = Request.QueryString[0];

    this.txtBox2.Text = Request.QueryString[1];

}

Some other ways to reach contents of QueryString.

foreach( string s in Request.QueryString)

{

     Response.Write(Request.QueryString[s]);

}

Or 

for (int i =0;i < Request.QueryString.Count;i++)

{

     Response.Write(Request.QueryString[i]);

}

Advantages of this approach

  1. It is very easy.

Disadvantages of this approach

  1. QueryString have a max length (most browser support 256 character), If you have to send large information this approach does not work.
  2. QueryString is visible in your address part of your browser so you should not use it with sensitive information.
  3. QueryString can not be used to send & and space characters.

0 comments:

Post a Comment

Related Posts with Thumbnails