Introduction
Sometimes we pass values from one page to other page in URL. QueryString is main object which helps to do the same.
Using code
QueryString - As per W3(WWW), a query string is the part of a uniform resource locator (URL)
containing data. The QueryString collection is used to retrieve the variable values in the HTTP query string. It is also considered as Client-Side state management technique in ASP.NET.
As a security, always encode header data or user input before using it. A method for encoding data is Server.HTMLEncode() and for decode use
Server.HTMLDecode().
The QueryString is specified by the values following the question mark (?), like this:
http://localhost:1997/WebForm1.aspx?id=10&name=manas
How to get all Keys and Values
Option 1: Using AllKeys properties
- foreach (var cookieKey in Request.QueryString.AllKeys)
- {
- Response.Write("Key: " + cookieKey + ", Value:" + Request.QueryString[cookieKey]);
- }
Option 2: Using no of QueryString Count
- for (int idx = 0; idx < Request.QueryString.Count; idx++)
- {
- Response.Write("Value:" + Request.QueryString[idx]);
- }
Option 3: Using Keys Count
- for (int idx = 0; idx < Request.QueryString.Keys.Count; idx++)
- {
- Response.Write("Key: " + Request.QueryString.Keys[idx] +
- ", Value:" + Request.QueryString[Request.QueryString.Keys[idx]]);
- }
If you want to get querystring value as string:
- string temp = Request.QueryString.ToString();
How to check a key is present:
Sometimes we check whether a key is present in QueryString. Below are two ways to check key is available in QueryString:
Option 1: Using AllKeys properties
- Request.QueryString.AllKeys.Contains("name");
- Request.QueryString.AllKeys.Contains("name1");
- Request.QueryString.AllKeys.Contains("Name");
Option 2 : Using NULL checking
- if(Request.QueryString["name"] != null)
- {
-
- }
We have HasKeys properties of QueryString which provides whether any keys is present. If there is no QueryString value then it returns false.
-
- Request.QueryString.HasKeys();
-
-
- Request.QueryString.HasKeys();
Conclusion
We discussed how to get all cookies are available in a page.
Hope this helps.