QueryString class useful for querystring manipulation, appendage, etc
posted on Wednesday, February 08, 2006 by bobby @ 12:36 pm
This little gem allows you to modify the querystring rather simply. Call QueryString.FromCurrent() to get a QueryString object populated from the current context.

Add, remove and edit the collection with ease. Just call .ToString() when you are ready to write it out.

Copy code to clipboard in IE or select code for Firefox
public class QueryString : NameValueCollection
{
    private string document;

    public string Document
    {
        get
        {
            return document;
        }
    }
    
    public QueryString()
    {
    }

    public QueryString(NameValueCollection clone) : base(clone)
    {
    }

    public static QueryString FromCurrent()
    {
        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;

        string[] keys = parts[1].Split("&".ToCharArray());

        foreach(string key in keys)
        {
            string[] part = key.Split("=".ToCharArray());

            if(part.Length == 1)
                qs.Add(part[0], "");

            qs.Add(part[0], part[1]);
        }

        return qs;
    }

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

    public void ClearAllExcept(string[] except)
    {
        ArrayList toRemove = new ArrayList();
        foreach(string s in this.AllKeys)
        {
            foreach(string e in except)
            {
                if(s.ToLower() == e.ToLower())
                    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()
    {
        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;
    }
}


CommentsComments
posted on Wednesday, February 08, 2006  by Jesse Gavin @ 5:26 AM

Thanks. There is also another one out there that Uwe Keim created. I use that a lot.
http://www.codeproject.com/aspnet/SimpleQueryString.asp
posted on Thursday, March 02, 2006  by ddw @ 10:32 AM

How did you get the code in the Blog nicely formatted? I am a new comer to Blogger, but an old hand in programming.
posted on Thursday, March 02, 2006  by bobby @ 10:33 AM

Well, this is not run by blogger (see here), it's run by my own blogging framework.

The code is formatted w/ the Highlighter .NET component.
posted on Monday, April 03, 2006  by Senixon @ 2:57 AM

Does your class provide a way to access the anchor element ie: #my_anchor
posted on Sunday, April 16, 2006  by bobby @ 3:32 PM

No, I didn't add that in.
posted on Monday, June 26, 2006  by jason @ 10:31 AM

Nice, although I would change:

HttpContext.Current.Server.UrlEncode(this[keys[ i ]]);

to

HttpUtility.UrlEncode(this[keys[ i ]]);

because the context might not always be available for a request, such as when processing a request through an HttpModule or an asynchronous call.
posted on Monday, June 26, 2006  by bobby @ 10:34 AM

Agreed. Good find. Fixed.
posted on Tuesday, July 04, 2006  by digitaljhelms @ 12:17 PM

Senixon's inquiry concerning access to the anchor element of the url is also what I was interested in. DDL in Flash using .NET would be a breeze with this QueryString class, however a lot of DDL solutions that developers come up with are based on the use of anchors. Any plans to implement such functionality into this class?
posted on Wednesday, January 23, 2008  by Anonymous @ 3:03 PM

...
posted on Saturday, March 22, 2008  by Scott @ 12:47 AM

Very handy! However have you tested your ClearExcept method? I have qs variable p that I want kept so I called ClearExcept("p") and it was the only thing removed!!
So I rewrote it to this:

public QueryString ClearAllExcept(string[] except)
{
foreach (string s in this.AllKeys)
{
bool remove = true;
foreach (string e in except)
{
if (s.ToLower() == e.ToLower())
{
remove = false;
break;
}
}
if (remove) this.Remove(s);
}
return this;
}

Either we've got symantic differences or I don't think the method in your post will do what it sounds like it should

Also I changed all of the return values of void to return the current QueryString. That way you can use it very similarly to the string class.
eg:

string bob = QueryString.GetCurrent().ClearExcept("p").Add("q", 1).ToString();

Also, I overloaded the add method to take an int in the second parameter as so often variables in qs' are ints. Probably can do something clever with generics there but was in a hurry.

Cheers!
posted on Sunday, April 06, 2008  by AC @ 8:20 PM

I realize this is 2+ years after you wrote it, but you should consider a StringBuilder for performance in ToString() implementation. All those string concatenations are killers.

Additionally, in ClearAllExcept(), instead of s.ToLower() == e.ToLower() consider:


if( s.Equals(e, StringComparison.InvariantCultureIgnoreCase) )


It's more portable, explicit, avoids 2 extra string allocations, and is probably faster.
posted on Monday, November 03, 2008  by juanalo @ 8:44 AM

This solution has a small bug when working with encrypted parameteres in the QueryString.

Using this line, will fix this problem:
string[] part = key.Split("=".ToCharArray(), 2);
posted on Monday, December 08, 2008  by Anonymous @ 10:31 AM

Adding this will allow you to derive the value of a selected key value pair

public string GetValue(string sKey)
{
string sOut = "";
if (this[sKey] == null)
{ }
else
{
sOut = this[sKey];
}
return sOut;
}


New Post Notification

Search Posts

Recent Posts


About Meeself
People call me Bobby DeRosa
I live somewhere in San Diego, CA
MCSD, MCAD, MCP

This theme was adapted from fUnique by fahlstad        Icons by FamFamFam        XHTML 1.0 Strict; tuned for Mozilla-powered browsers

Admin Login Administrator Login
Invalid login attempts are logged.
  Username:
  Password: