posts - 81, comments - 208, trackbacks - 0

C# Extension Methods for ASP.NET Query String Operations


Over the years, all the way back to the ASP 2.0 days, elegantly handling the Query String parameters between gets has been a challenge. With Web Forms for ASP.NET View State put this issue on the backburner, but with MVC on the rise and restful applications becoming hot, Query String parameters have come back to the forefront.

For an example of where the Query String parameters can get cumbersome, consider a web page which lists products. At the least the page would have paging support, most sites with paging by query string parameters (something like "?page=1"). Now add to the navigation sorting and custom filtering. Depending on the complexity of the sorting you can easily have Query Strings starting to look like "?page=1&sort_col=name&dir=asc&filterby=desc&filter=custom%20filter". While the Query String itself is not complex, the dynamic nature of it can become cumbersome and blotted within the code. Who wants to write the series of conditionals building the custom expression (for each link)? I certainly don't do it; the process is too mechanical for my taste.

To solve this, I explored using an Extension Method upon NameValueCollection, the type for Request.QueryString. Doing this allowed for a pipe like syntax best demonstrated with an example.


Note what is occurring in the code above. The original query string is being conditionally appended or updated based upon some inline form validation. To me the syntax is much cleaner and presents less bloat than a few conditionals for each field (does the field exist? Should I add it or update it? Etc).

Please feel free to grab a copy of the extension methods here, just let me know if you have any feedback!

using System;

using System.Collections.Specialized;

using System.Text;

 

namespace CustomExtension

{

    public static class Extensions

    {

        public static string WriteLocalPathWithQuery(

            this NameValueCollection collection, Uri Url)

        {

            if (collection.Count == 0)

                return Url.LocalPath;

 

            StringBuilder sb = new StringBuilder(Url.LocalPath);

            sb.Append("?");

 

            for (int i = 0; i < collection.Keys.Count; i++)

            {

                if (i != 0)

                    sb.Append("&");

                sb.Append(

                    String.Format("{0}={1}",

                    collection.Keys[i], collection[i])

                );

            }

            return sb.ToString();

        }

 

        public static NameValueCollection ChangeField(this NameValueCollection collection,

            string Key, string Value)

        {

            return ChangeField(collection, Key, Value, true);

        }

 

        public static NameValueCollection ChangeField(this NameValueCollection collection,

            string Key, string Value, bool Allow)

        {

            if (Allow)

            {

                if (!String.IsNullOrEmpty(collection[Key]))

                    collection[Key] = Value;

                else

                    collection.Add(Key, Value);

            }

 

            else //remove the value all together

            {

                if (!String.IsNullOrEmpty(collection[Key]))

                    collection.Remove(Key);

            }

            return collection;

        }

 

        public static NameValueCollection Duplicate(this NameValueCollection source)

        {

            NameValueCollection collection = new NameValueCollection();

            foreach (string key in source)

                collection.Add(key, source[key]);

            return collection;

        }

    }

}


Print | posted on Wednesday, July 23, 2008 2:37 PM | Filed Under [ Web Programming ]

Feedback

Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

Cool
1/21/2009 4:52 PM | Softer
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

Ditto
5/14/2009 5:00 PM | Ida
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

The Code is very helpful especially for fresher.Keep on posting helpful articles, tips and tricks.
9/24/2010 1:08 AM | accepted online casinos to play
Gravatar

# Treat Bedbugs

I have heard about these problems in corporate websites,Offshore Software development might help you to deal with them.
4/28/2012 4:57 AM | Treat Bedbugs
Gravatar

# theiconic Shoes online


The blog is absolutely fantastic. Lots of great information and inspiration, both of which we all need. Thanks
5/12/2012 7:04 AM | theiconic Shoes online
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

It is a very good blog Thanks to give the nice information of all people I like this
5/14/2012 4:11 AM | perfume2order
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

This page is very informative and fun to read. I appreciated what you have done here.
5/14/2012 9:43 AM | Interior decorators in delhi
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

This page is very informative and fun to read. I appreciated what you have done here.
I enjoyed every little bit part of it. I am always searching for informative information like this.
5/17/2012 5:13 AM | best architect in delhi
Gravatar

# طراحی سایت

How is possible to write this article ? it is very very informative and helpful for the people.I like it very much.Thanks a lot .
6/22/2012 2:33 AM | طراحی سایت
Gravatar

# hi

This is my first to deal with hardship in gaining information about hybrid annuity but I get rewarded when I came across this challenging C# Extension Methods for ASP.NET Query String Operations. Amazing! The person guiding this has an incredible mind. Click here to grasp more details!
7/4/2012 5:37 AM | Click here
Gravatar

# Bill

After reading this post I felt that you have done a lot of research on the topic,and provide you good quality insight. Thank you.
7/28/2012 11:47 PM | Bill Walsh
Gravatar

# office refurbishment by The Interiors Group in London

Surfing the internet has constantly been one of my pastimes. I saw this nice blog and I got to discover a ton from it consisting of the benefits of office refurbishment by The Interiors Group in London. I truly appreciate blog writers who make the effort to writer appropriate information. Your blog site, on the other hand, is fantastic. Kudos!
9/7/2012 3:25 AM | Ludwig Curzi
Gravatar

# Russian roulette game

This info is very much impression for the nice technology is visible in this blog. This info is very excellent that to concept wise visible in this website .Thanks a lot for providing the different tips in this blog.

Online bingo
Roulette cam
Roulette man
Russian roulette online game
Gambling licence
10/3/2012 4:38 AM | angelicarojas
Gravatar

# ugg saappaat

Uggs boots keep feet toasty even http://www.uggssaappaatsuomi.org/ in the freezing cold days and ugg saappaat therefore have become the ugg saappaat suomesta first choices of many customers xiaocaicl15. ugg saappaat boots This kind of footwear looks fashionable ugg saappaat oulu and unique and is available in different uggs saarbrücken styles and colors for your choices. Made http://www.uggstovlerdanmark-s.com/ with twin-faced sheepskin, these boots feel incredible ugg boots udsalg warm and comfortable. Many celebrities are ugg boots dk also spotted wearing them during the winter season ugg boots tilbud to go through the cold winter. But this conception is ugg boots online quite wrong, as wearing them sensibly especially with jeans and feathery coats really looks cool and exquisite.
88
11/13/2012 3:16 AM | Zkjykgsng01
Gravatar

# Indian Wedding Cards

Very nice site and we bookmarked it for further use.
12/17/2012 11:17 PM | Indian Wedding Invitations
Gravatar

# Sikh Wedding Cards

Very nice blog and info for C# larners.
12/21/2012 2:41 AM | sikh wedding cards
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

Among my most popular pastimes is surfing the web due to the fact that I always find wonderful points to see and read. Lately, I saw this blog on Business Plan which grabbed my attention. Seeing blog site sites like yours makes me realize why I like surfing the internet.
1/7/2013 8:48 PM | Justine Miller
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

Geez! In all honesty, C# Extension Methods for ASP.NET Query String Operations is really impressive. I in fact found your website after inspecting green card by marriage websites.
1/11/2013 9:10 PM | Frank Beasley
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

I saw this blog site on Waterloo Structures a few days back and it excelled. Checking out informative realities online advises me that our education is never ever over. Check this out if you are intrigued to obtain more effective information and facts.
3/1/2013 8:48 PM | Justine Decker
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

I came across your web-site while I was web surfing for posts on Security Guards Jacksonville FL. The Extension Methods for ASP.NET Query String Operations is very remarkable and I will really tell my friends about it.
3/11/2013 5:03 AM | Winfred Lindsey
Gravatar

# Oakley Store

Side of the narrative of the article edge lyrical expression of emotion, not only take care Oakley Store

4/3/2013 1:55 AM | Oakley Store
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

I am always searching for informative information like this.keep on posting.Custom Dissertation Writing Service ^Writing agency UK ^how to get essay writers ^University Essays Help




5/21/2013 1:44 PM | Daniel
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

I really wanted to lose weight in an organic way. I'm glad I have actually learnt about Lycium Barbarum by reading charlesrcook. It's not simply a delectable berry but also the solution to my dilemma. Click Here for more information.
8/19/2013 8:10 PM | albeeath87
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

I had fun going over C# Extension Methods for ASP.NET Query String Operations whilst waiting for my turn right here at silver lake hair salon. It was totally very informational.
1/27/2014 7:39 PM | Donald Thrasher
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

I've been very burnt out hunting for Debt Settlement tips; and so I looked for articles only to rejuvenate my cognitive powers, and C# Extension Methods for ASP.NET Query String Operations really supplied me more than enough, regards.
2/2/2014 10:32 PM | Richard King
Gravatar

# re: C# Extension Methods for ASP.NET Query String Operations

I've had a tough time hunting for Josh Groban pieces in ITunes click here. Glad I was able to go through a few insightful elements at your blog; Right now I get a lot more energy.
2/13/2014 9:55 PM | Randal Porter

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 4 and 6 and type the answer here:

Powered by:
Powered By Subtext Powered By ASP.NET