Tuesday 17 January 2012

Query string in asp.net

Example url with querystring can be something similar like this

http://yourdomainname.com/defauld.aspx?variable1=value1&variable2=value2

Suppose we have a textbox txtData and we want it's value on other page
than in code behind we would write in click event of btnGo

private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" +
txtData.Text);
}

Or

1private void btnGO_Click(object sender, System.EventArgs e)
2{
3Response.Redirect("Default2.aspx?city=" +
4txtData.Text + "&country=" + txtcountry.Text);
5}


Now to retrieve these values on other page we need to use request.querystring, we can either retrieve them by variable name or by index

private void Page_Load(object sender,System.EventArgs e)
{
txtCity.Text = Request.QueryString["city"];
txtCountry.Text = Request.QueryString["country"];
}

Or we can also use

private void Page_Load(object sender,System.EventArgs e)
{
txtCity.Text = Request.QueryString[0];
txtCountry.Text = Request.QueryString[1];
}



QueryString can't be used for sending long data because it has a max lenght limit

Data being transferred is visible in url of browser

To use spaces and & in query string we need to replace space by %20 and & by %26


private void btnGO_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.aspx?Value=" +
txtData.Text.Replace(" ","%20");
}

Or we can use Server.UrlEncode method

private void btno_Click(object sender, System.EventArgs e)
{
Response.Redirect("Default2.Aspx?" +
Name=" + Server.UrlEncode(txtData.Text));
}

No comments:

Post a Comment