How To Get All QueryString Keys In ASP.NET

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
  1. foreach (var cookieKey in Request.QueryString.AllKeys)  
  2. {  
  3.     Response.Write("Key: " + cookieKey + ", Value:" + Request.QueryString[cookieKey]);  
  4. }  
Option 2: Using no of QueryString Count
  1. for (int idx = 0; idx < Request.QueryString.Count; idx++)  
  2. {  
  3.       Response.Write("Value:" + Request.QueryString[idx]);  
  4. }  
Option 3: Using Keys Count
  1. for (int idx = 0; idx < Request.QueryString.Keys.Count; idx++)  
  2. {  
  3. Response.Write("Key: " + Request.QueryString.Keys[idx] +  
  4. ", Value:" + Request.QueryString[Request.QueryString.Keys[idx]]);  
  5. }  
If you want to get querystring value as string: 
  1. string temp = Request.QueryString.ToString(); // id=10&name=manas  
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 
  1. Request.QueryString.AllKeys.Contains("name"); // Return true  
  2. Request.QueryString.AllKeys.Contains("name1"); // Return false  
  3. Request.QueryString.AllKeys.Contains("Name"); // Return false due to Case-sensitive  
Option 2 : Using NULL checking
  1. if(Request.QueryString["name"] != null)  
  2. {  
  3.     //your code that depends on requirement  
  4. }  
We have HasKeys properties of QueryString which provides whether any keys is present. If there is no QueryString value then it returns false.
  1. // http://localhost:1997/WebForm1.aspx?id=10&name=manas  
  2. Request.QueryString.HasKeys(); // true  
  3.   
  4. // http://localhost:1997/WebForm1.aspx  
  5. Request.QueryString.HasKeys(); // false  
Conclusion
 
We discussed how to get all cookies are available in a page.
 
Hope this helps.
Ebook Download
View all
Learn
View all