You want to see how to use the QueryStringcollection in the ASP.NET web development framework. Almost all examples show one way of using this NameValueCollection, but there are faster and more logical ways. This short information sheet has some examples and tips with QueryString, using the C# programming language.
Use QueryString
Here we see an .aspx Web Forms page that executes when the user accesses Default.aspx. The code here is the code-behind part, Default.aspx.cs, and it is written in the C# programming language. To test the above code, run the page in the web browser on the ASP.NET development server. It will be completely blank. Try adding the string "?param=dotnet" at the end of the URL.
QueryString example [C#] using System; using System.Web.UI; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { string v = Request.QueryString["param"]; if (v != null) { Response.Write("param is "); Response.Write(v); } } } Program result It prints value of param query. The screenshot shows the result.
Two query string parameters
Here we see how you can test two query string URL parameters. Another common requirement is to test two different query strings. You may have to use either one or both at once. The next example here has some inefficiencies, but it works well otherwise.
QueryString example with multiple parameters [C#] using System; using System.Web.UI; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { string v = Request.QueryString["param"]; if (v != null) { Response.Write("param is "); Response.Write(v); } string x = Request.QueryString["id"]; if (x != null) { Response.Write(" id detected"); } } } Test code with this url: ?param=first&id=true
Testing the code. Try the above example code by typing, at the end of the URL in Internet Explorer or Firefox, the test url. The above string specifies that the "param" query is equal to "first", while the "id" param is equal to "true". Always be careful with the "id" query string, as Google's spiders may avoid it.
Advanced example
The Request.QueryString collection is a NameValueCollection internally. QueryString is implemented as a property getter for an internal NameValueCollection. The NameValueCollection is a specialized collection that has a somewhat unusual implementation. MSDN describes it as a "collection of associated String keys and String values that can be accessed either with the key or with the index."
msdn.microsoft.comTesting the QueryString collection. My testing indicates that using the index to access a value in NameValueCollection is far faster than using the ["string"] syntax.
Page that uses HasKeys() on QueryString [C#] using System; using System.Web.UI; using System.Collections.Specialized; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { // 1 // Get collection NameValueCollection n = Request.QueryString; // 2 // See if any query string exists if (n.HasKeys()) { // 3 // Get first key and value string k = n.GetKey(0); string v = n.Get(0); // 4 // Test different keys if (k == "param") { Response.Write("param is " + v); } if (k == "id") { Response.Write("id is " + v); } } } }
Overview. In step one, this code gets a reference to the QueryString collection. In high-performance code, you want to avoid excessive property lookups.
Next steps in the code. In step two, we use the HasKeys() method on QueryString. This is very useful for telling whether there are any query string keys available on the URL. In step four, we do two lookups on the NameValueCollection to get the very first key and the very first value. Because we only access the first key and value, this code doesn't work for more than one key value pair.
NameValueCollection
This article is really more about NameValueCollection than QueryString, as QueryString is simply an instance of NameValueCollection. You can find more detailed information about this collection on this site.
NameValueCollection UsageOptimizations
Here I benchmarked the query string code examples. The benchmark simply reads the very first query string key/value pair from the URL. My requirement was to accept only the first query string on a page.
Example that uses HasKeys()... [Method A] [C#] using System; using System.Web; using System.Web.UI; using System.Collections.Specialized; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { HttpRequest q = Request; NameValueCollection n = q.QueryString; if (n.HasKeys()) { string k = n.GetKey(0); if (k == "one") { string v = n.Get(0); } if (k == "two") { string v = n.Get(0); } } } } Example that uses QueryString["key"] syntax... [Method B] [C#] using System; using System.Web; using System.Web.UI; using System.Collections.Specialized; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { HttpRequest q = Request; string v = q.QueryString["one"]; if (v != null) { } v = q.QueryString["two"]; if (v != null) { } } }
Discussion. What we see is that when you only need to access the first query string key/value pair, using HasKeys(), Get(), and GetKey() is lots faster than the QueryString["string"] approach.
No query string Method A: 0.08 s Method B: 1.75 s Matching query string Method A: 0.45 s Method B: 2.80 s No matching query string Method A: 0.46 s Method B: 1.73 s
Is QueryString filled lazily?
No. I found that by the time your HttpRequest is being used, the QueryString collection has already been initialized with all the query key/value pairs. I looked at the locals in the Visual Studio debugger to find this. Therefore, the analysis in this article is correct and the faster method shown is really considerably faster than the naive approach.
Visual Studio Debugging TutorialNotes
When you use QueryString in Global.asax or another "hot" path in your code, it pays to optimize the logic. When your website runs the code several times each second, you need it to be as fast as possible.
Summary
We saw several examples of Request.QueryString, using the same code pattern that most ASP.NET tutorials use. However, we also noted how you can use other methods on QueryString to gain a substantial performance increase.
.....................................................................................................
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=Atilla&lastName=Ozgur
This html addresses use
QueryString
property to pass values between pages. In this address you send 3 information.- Webform2.aspx this is the page your browser will go.
name=Atilla
you send a name variable which is set to AtillalastName=Ozgur
you send a lastName variable which is set to Ozgur
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
- It is very easy.
Disadvantages of this approach
QueryString
have a max length, If you have to send a lot information this approach does not work.QueryString
is visible in your address part of your browser so you should not use it with sensitive information.QueryString
can not be used to send & and space characters.
If you write this code and try them you will see that you have a problems with space and & characters, e.g. if you need to send a variable which contains & such as "Mark & Spencer". There must be a solution for this problem. If you look to Google�s query string you will see that it contains a lot of %20. This is the solution of our third disadvantage. Replace space with %20 and & with %26 for example.
private void btnSubmit_Click(object sender, System.EventArgs e)
{
string p1 = this.txtName.Text.Replace("&","%26");
p1 = this.txtName.Text.Replace(" ","%20");
string p2 = this.txtLastName.Text.Replace("&","%26");
p2 = this.txtName.Text.Replace(" ","%20");
"WebForm2.aspx?" +
"Name=" + p1 +
"&LastName=" + p2;
Response.Redirect(p2);
}
Since this is a such a common problem Asp.Net should have some way to solve. There it is
Server.UrlEncode
. Server.UrlEncode
method changes your query strings to so that they will not create problems.private void btnSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("WebForm2.Aspx?" +
"Name=" + Server.UrlEncode(this.txtName.Text) +
"&LastName=" + Server.UrlEncode(this.txtLastName.Text));
}
Same solution is in Microsoft .Net Quick Start tutorials.
ASP.NET --- Working with Web Controls ---
--- Performing Page Navigation (Scenario 1) ---
--- Performing Page Navigation (Scenario 2) ---
Look at them also if you want to see more example for this technique. Also I advise you to look at Alex Beynenson's article about building
QueryString
(s).
1 comments:
Really nice and informative thanks for sharing this.
Web Development Company
Post a Comment