I am a danish programmer living in Bangkok.
Read more about me @ rasmus.rummel.dk.
Webmodelling Home > ASP.NET > C# & Javascript QueryString Class

C# QueryString class

Updated Mar 2013. Working with the query string in .net have always been cumbersome, which is somewhat strange taking into account how much query string manipulation is going on.

Eventually I stumpled upon a query string utility class (long forgotten by who) and decided to pick it up. It turned out to be a really handy class to have and as I use it in nearly all my projects, I have taken the liberty to edit a little in the class to fit my needs as I go along - a true gem I hope others can benefit from as well.

Actually I grew so happy for this small class that I made a Javascript version (it is not in use as often but sometimes it is nice to have).

Using this class for years, I think others could benefit from it also - please download, edit and use.


Download C# Class        Download Javascript Class

Usage :

  • Instantiation :
    • CSharp
      • QueryString qs = QueryString.FromCurrent(); //most used instantiation as it will initialize with current url
      • QueryString qs = QueryString.FromUrl("url");
    • Javascript
      • var qs = QueryString.FromCurrent();
      • var qs = QueryString.FromUrl("url");
  • Adding & removing keys :
    • CSharp
      • qs.Add("key","value"); //if key already exists, it will get the new value
      • qs.Remove("key"); //if key does not exist, no harm done
      • qs.Clean("prefix"); //remove all keys that starts with "prefix" - imagine you write a control that use its own query string keys but you don't want to delete whatever keys are set by the host page
      • qs.ClearAllExcept(new string[]{"key1","key2"}); //remove all keys except those specified
      • qs.Clear(); //ok, just remove all keys
    • Javascript
      • qs.Add("key","value");
      • qs.Remove("key");
      • qs.Clean("prefix");
      • qs.ClearAllExcept(["key1","key2"]);
      • qs.Clear();
  • Getting key values :
    • CSharp
      • string value = qs["key"];
    • Javascript
      • var value = qs.params["key"];
  • Usage examples :
    • CSharp
      • myLink.NavigateUrl = qs.ToString(true); //prefixes the query string with the document url (used to initialize the QueryString)
      • myLink.NavigateUrl = Request.Url.AbsolutePath + qs.ToString(); //qs.ToString() is only outputting the query string part of the initialization url
    • Javascript
      • myLink.href = qs.ToString(true);
      • myLink.href = document.location.href.split('#')[0].split('?')[0] + qs.ToString();

Ok, let's see the code : (here C#, if you want to see the Javascript code, just download the Javascript file above)

using System;
using System.Web;
using System.Collections;
using System.Collections.Specialized;

public class QueryString : NameValueCollection
{
	private string document; //stores the url part before the query string in case we want to use it later
	public string Document
	{
		get { return document; }
	}

	public QueryString() {} //mostly for internal usage

	public static QueryString FromCurrent() //this is the typical function to use for instantiation, it initializes QueryString with current url
	{
		return FromUrl(HttpContext.Current.Request.Url.AbsoluteUri);
	}

	public static QueryString FromUrl(string url)
	{
		string[] parts = url.Split("?".ToCharArray());
		QueryString qs = new QueryString();
		qs.document = parts[0];
 
		if (parts.Length == 1)
			return qs;
 
		NameValueCollection nvcQueryString = HttpUtility.ParseQueryString(parts[1]);
		foreach (string key in nvcQueryString)
		{
			qs.Add(key, nvcQueryString[key]);
		}
 
		return qs;
	}

	public void ClearAllExcept(string except)
	{
		ClearAllExcept(new string[] { except });
	}

	public void ClearAllExcept(string[] except)
	{
		ArrayList toRemove = new ArrayList();
		foreach (string key in this.AllKeys)
		{
			bool removeKey = true;
			foreach (string keyToKeep in except)
			{
				if (key.ToLower() == keyToKeep.ToLower()) 
				{
					removeKey = false;
					break;
				}
			}
			if (removeKey)
			{
				toRemove.Add(key);
			}
		}
 
		foreach (string s in toRemove)
			this.Remove(s);
	}

	/// <summary>
	/// Removes all keys starting with pPrefix
	/// </summary>
	/// <param name="pPrefix"></param>
	public void Clean(string pPrefix)
	{
		ArrayList toRemove = new ArrayList();
		foreach (string s in this.AllKeys)
		{
			if (s.ToLower().StartsWith(pPrefix))
			{
				if (!toRemove.Contains(s))
				{
					toRemove.Add(s);
				}
			}
		}
 
		foreach (string s in toRemove)
		{
			this.Remove(s);
		}
	}

	public override void Add(string name, string value)
	{
		if (this[name] != null)
			this[name] = value;
		else
			base.Add(name, value);
	}

	public override string ToString() //use this function to write out the query string part of eg. HyperLink.NavigateUrl
	{
		return ToString(false);
	}

	public string ToString(bool includeUrl)
	{
		string[] parts = new string[this.Count];
		string[] keys = this.AllKeys;
 
		for (int i = 0; i < keys.Length; i++)
			parts[i] = keys[i] + "=" + HttpUtility.UrlEncode(this[keys[i]]);
 
		string url = String.Join("&", parts);
 
		if (!string.IsNullOrEmpty(url) && !url.StartsWith("?"))
			url = "?" + url;
 
		if (includeUrl)
			url = this.document + url;
 
		return url;
	}
}

Comments

You can comment without logging in
 
 B  U  I  S 
Words: Chars: Chars left: 
 Captcha 
 Nickname
Facebook
    
Reza
--------------
      report  reply  
You can also make it better by using:
NameValueCollection parts = HttpUtility.ParseQueryString(querystring);

Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 108
--------------
      report  reply  

Hi Reza

Thanks for bringing my attention to HttpUtility.ParseQuery and you are right, I can use it to optimize QueryString.FromUrl (if that was what you had in mind).

The new FromUrl(string url) function : (old code in green, new code in blue)
  public static QueryString FromUrl(string url)
  {
    string[] parts = url.Split("?".ToCharArray());
    QueryString qs = new QueryString();
    qs.document = parts[0];
 
    if (parts.Length == 1)
      return qs;
 
    //OLD CODE
    string[] keys = parts[1].Split("&".ToCharArray());
    foreach (string key in keys)
    {
      string[] part = key.Split("=".ToCharArray());
      if (part.Length > 1)
      {
         qs.Add(part[0], part[1]);
      }
      else
      {
         qs.Add(part[0], "");
      }
    }

 
    //NEW CODE
    NameValueCollection nvcQueryString = HttpUtility.ParseQueryString(url);
    foreach (string key in nvcQueryString)
    {
      qs.Add(key, nvcQueryString[key]);
    }

 
    return qs;
  }

Actually if the querystring contained a bookmark, the old code would get a wrong value for the last querystring key, since I did not split away any hash (#) part, the new code should solve that problem as well.

I have updated the download files, the c# version having the HttpUtility.ParseQuery optimization and the javascript version having the hash split solution.

web fiddler by nature



click to top