posts - 64, comments - 387, trackbacks - 4

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 reason I'm tying it to the specific enum is to not clutter the api, and possibly confuse someone that it's a method that's part of the .net framework. I'm just mostly using Extension Methods with caution since I'm not sure the the full impact would be of using too many extension methods that would possibly interfere with each other.
7/16/2009 7:07 AM | winning poker hands
Gravatar

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

really cool
1/28/2010 1:17 AM | Andy
Gravatar

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

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.
4/24/2010 12:42 AM | Keno Tips und Tricks
Gravatar

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

The extension code you posted here is very helpful to others especially to beginner programmers of ASP.NET. Keep on posting helpful articles, tips and tricks. Cheers!
4/24/2010 11:34 PM | Kids Games
Gravatar

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

Thank you, great code.
4/27/2010 7:35 AM | Ben10 games
Gravatar

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

You saved me hours of work. thank you.
4/27/2010 7:37 AM | fashion games
Gravatar

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

A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are some nifty details you need to take care of like, appending an & if not the first parameter, encoding the parameters etc.....
5/10/2010 7:10 AM | giochi del casino
Gravatar

# piyush group

nice post i had bookmarked your blog, feel free to visit my blog at piyush group.


5/22/2010 6:50 AM | piyush group
Gravatar

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

Thanks for your kind coding
5/28/2010 12:10 AM | Bearings
Gravatar

# los angeles web design

Nice coding.I have found my solution here.
9/2/2010 3:09 AM | los angeles web design
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

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

Cool! I love the information you shared. I have found the new solution to my problems. The codes you posted are really working on my site.
10/4/2010 6:30 AM | minn kota powerdrive 55
Gravatar

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

thank you . it give me more information from your article
10/18/2010 2:59 AM | blueskiss2010
Gravatar

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

I am happy to find this post very useful for me, as it contains lot of information. I always prefer to read the quality content and this thing I found in you post. Thanks for sharing
10/22/2010 8:14 PM | itunes gift card canada
Gravatar

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

I am happy to learn about Query Strings ,it is well executed site.and easily applicable.
Thanks for this.
curt
nike blazer
1/2/2011 8:29 AM | willsonn
Gravatar

# re: Document Management Software

Thanks for post. It's really informative stuff. I really like to read.Hope to learn a lot and have a nice experience here! my best regards guys
1/11/2011 6:28 AM | Document Management Software
Gravatar

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

Great post and thank you for including the lines of code for clarification. I blog on bankruptcy attorneys.
1/18/2011 4:01 PM | Ahren Tiller
Gravatar

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

It appears to work well with Opera, I'm using Opera to write this post now.
1/21/2011 1:49 PM | Charles
Gravatar

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

This is a really good post. Monster beats by dre headphone
Monster beats solo Hd headphone
Must admit that you are amongst the best bloggers I have read. Thanks for posting this informative article.
12/12/2011 7:30 PM | Monster beats solo hd red headph
Gravatar

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

Thanks for publish. It's really useful products. I really like to study.Hope to master a lot and have a awesome practical knowledge here! my best regards guys.
12/13/2011 4:30 AM | flatulence treatment
Gravatar

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

This is very much interesting info in this blog. I am very much happy for visiting the nice technology in this blog. Thanks a lot for sharing the nice info in this blog. I had really like it.
12/13/2011 8:19 AM | Toronto Escorts
Gravatar

# Paradise8

Submitted different blogs on-line and give us complete information regarding the topic on-line.
Paradise8
12/14/2011 5:58 AM | Paradise8
Gravatar

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

this gives various info.. thanks for that! deer antler velvet
12/14/2011 8:31 PM | deer antler velvet
Gravatar

# unitech world spa gurgaon

Well, someone will have to understand the language. The general idea is this: each item displayed on the screen is identified by an ID. Each user has a locale. You then use that ID and locale to retrieve the text for the screen in the user's language.
12/17/2011 2:01 AM | Kalra 123
Gravatar

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

Thanks for this code!It helps me a lot.
12/20/2011 5:38 AM | lap band los angeles
Gravatar

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

This is really like this info in this blog that to very enjoyed for the nice technology in this blog. I have to search for one thing info in this blog. Thanks a lot for sharing the nice info in this blog.
12/21/2011 2:36 AM | Search Engine Optimization
Gravatar

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

I am really very happy for visiting the nice info in this website that to great technology in this website. Thank you very much for providing the nice info in this website that using the great service in this blog.
12/22/2011 1:11 AM | Search Engine Optimization
Gravatar

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

Good work. I used to be checking constantly this blog and I am inspired! Very useful information specially the last part. I take care of such information much. I used to be seeking this particular information for a long time. Thank you for sharing.
12/22/2011 6:49 AM | Buy domain name
Gravatar

# Best link building services

This website is providing the nice info in this blog that to helpful info in this blog. I am really very proved for visiting the nice technology in this blog. I had really like it very much for visiting the nice info in this blog. This website is providing the number articles in this blog that to simple language for visiting the nice info in this blog. Thank you very much for providing the nice info in this blog.
12/22/2011 8:17 AM | Best link building services
Gravatar

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

Write a program that prompts for and reads a single character stiring that will consist of a first name, a space and a last name. Output this string on one line, and on the next line output the last name, followed by a comma, a space, and the first name.
12/24/2011 1:22 AM | stag do weekends
Gravatar

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

Nice post
12/24/2011 6:59 AM | Casino Jack
Gravatar

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

I would like to congratulate the author for his brilliant efforts in putting this article together. incontinence products He deserves appreciation for his hard work. Thanks
12/27/2011 4:40 PM | Havemøbler
Gravatar

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

If you are a plus size bride, brown bridesmaid dresses you'll be trying to find a great plus size wedding dress. cocktail dress Today's plus size bride has her choice of numerous stunning plus size wedding dresses. From classic to modern junior bridesmaid dresses towards the entirely special - you will often uncover a lovely plus size wedding dress which is perfect to say, "I do" on that unique day. The plus size bride today can appear spectacular, radiant and even glamorous when she chooses her wedding dress. No worry more affordable bridesmaid dresses than locating just frumpy frocks!
12/28/2011 12:11 AM | jamieboyd
Gravatar

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

This website is really very happy for visiting the nice info in this blog. This is very much interesting info in this blog and really enjoyed for visiting the great technology in this blog. Thanks a lot for sharing the nice info in this blog.
12/28/2011 3:10 AM | Online strip poker
Gravatar

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

I study this publish finish and think that the content of this publish is wonderful and clear and understandable.
12/28/2011 3:15 AM | Buy Idol lash
Gravatar

# 3C Sector 89 Gurgaon

wine Influenza (swine flu) is a respiratory disease of pigs caused by type A influenza viruses that causes regular outbreaks in pigs. People do not normally get swine flu, but human infections can and do happen. Swine flu viruses have been reported to spread from person-to-person, but in the past, this transmission was limited and not sustained beyond three people.
12/28/2011 6:44 AM | 3C Sector 89 Gurgaon
Gravatar

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

I am thank you for presenting the different articles in this blog that to helpful info in this blog. This website is providing the wonderful info in this blog that to nice services in this blog.
12/28/2011 9:05 AM | Euro poker
Gravatar

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

This is very much satisfied by the technology in this blog that to nice services in this blog. It was really helpful info in this blog that to very happy for providing the nice technology in this blog.
12/28/2011 9:13 AM | Poker sets
Gravatar

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

This website maintained is very easy that to using the great technology in this website. This is really very happy for sharing the nice info in this blog. Thanks a lot for providing the amazing info in this blog.
12/28/2011 9:14 AM | online casino slots
Gravatar

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

Nice services are display in this blog that to sharing the nice info is display in this blog. Thanks a lot for using the amazing services in this blog that to using the great info in this blog.
12/29/2011 3:44 AM | Online Gambling
Gravatar

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

I am really admired for the great approach is visible in this blog that to nice articles are display in this blog. Thanks a lot for using the nice services are display in this blog.
12/29/2011 3:46 AM | Gambling addictions
Gravatar

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

Very useful, thank you for share the article with us.
1/1/2012 2:06 PM | Cloud Application Development
Gravatar

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

Different people in every country take the personal loans from various banks, just because it is easy.
1/2/2012 9:35 PM | HOLCOMB26ETHEL
Gravatar

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

The best way to receive the good facts connected with this good post is to buy an essay. So, don’t throw away you academic time and cash, just buy research papers to be free!
1/9/2012 3:31 AM | DEANASnow35
Gravatar

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

Writing services do nice custom essay service about this topic and the very interesting stuff about contact us, some students should get without money!
1/11/2012 6:54 AM | AidaRobinson
Gravatar

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

To accomplish such article is not simple though you cope with that. If every writer was as good as you are, all students will never have great problems with the essay papers.
1/11/2012 7:02 AM | LynnettePratt25
Gravatar

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

However, they can also buy facebook likes as an initial source of online business promotion.It was very difficult for me to handle my business crises; happening from past few months. It was my last try to boost my business promotion and I decided to buy facebook fans from www.fanbullet.com. Today, I have a successful business setup without any crises.
1/11/2012 8:14 AM | Buy facebook likes
Gravatar

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

Nice article, I am a big time fan of your site, keep up the nice work, and I will be a frequent visitor for a very long time.Edmonton Latisse
1/11/2012 4:02 PM | Edmonton Latisse
Gravatar

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

Nice info. good blog.
1/13/2012 12:28 AM | Indian Wedding Cards
Gravatar

# artificial grass


The blog was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog,looking forward for more contents...Great job, keep it up..
1/16/2012 5:08 AM | artificial grass
Gravatar

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

Good post....thanks for sharing... Very useful for me i will bookmark this for my future needs. Thanks
1/18/2012 2:39 AM | godrej 104
Gravatar

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

ASP.NET and Microsoft data platform and serves as a Senior .Net Consultant and Architect at Sela Group. He is a Microsoft data platform MVP and a certified Enterprise Application Developer. Gil has worked in the past in variety of positions and projects as a leading developer, team leader, consultant and more. His interests include Entity Framework, Enterprise Library, LINQ, ADO.NET and many other new technologies from Microsoft.
1/18/2012 4:31 AM | Carports Perth
Gravatar

# pioneer group apartment gurgaon

Pioneer Araya offers affordable 3, 4 & 5 BHK apartment at sector 62 Gurgaon. Pioneer Araya Gurgaon comprises of 4 towers with each tower consisting of 30-35 floors each and each of the floors have 2 flats each. Pioneer Araya Gurgaon providing all modern facilities.
1/19/2012 3:25 AM | ybisht
Gravatar

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

I am a a high school student and I require lots of cash to waste for various issues. Thus, I never strive to utilize expensive essay writing service. I need reasonable prices for custom academic papers!
1/21/2012 4:40 AM | Donovan22Charmaine
Gravatar

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

Nice share you have given to us with such an large collection of information. Great work you have done by sharing them to all. simply superb
1/22/2012 3:04 PM | privathospital
Gravatar

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

I am absolutely amazed at how terrific the stuff is on this site.
1/22/2012 3:06 PM | Hus i Thailand
Gravatar

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

I know that my essays writing skills are poor. I cannot improve my skills if I get know How To Buy An Essay. What must I do? Maybe I have to turn to real professionals
1/22/2012 10:49 PM | Kristie21Kim
Gravatar

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

How to use insert query in asp.net for ms access database? can any one say?
1/23/2012 5:49 AM | Promotional gifts
Gravatar

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

The expansion code you published here is very employed to others especially to newbie developers of ASP.NET. Keep on publishing beneficial articles.
1/25/2012 2:54 AM | get rid of incontinence
Gravatar

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

Thank you for putting up awesome written content and then keep up the excellent posting great stuff.
1/27/2012 5:35 AM | purchase domain name
Gravatar

# SWAROVSKI BEADS

Can I just say what a relief to find someone who actually is aware of what theyre talking about on the internet. You positively know how to bring a difficulty to gentle and make it important. More folks must learn this and perceive this aspect of the story. I cant consider youre not more fashionable since you undoubtedly have the gift.
1/27/2012 6:52 AM | SWAROVSKI BEADS
Gravatar

# Mens Diamond Watches

First of all i would like to thank you for the great and informative entry. I have to admit that I have never heard about this information. I have noticed many new facts for me. Thanks a lot for sharing this useful and attractive information and I will be waiting for other interesting posts from you in the nearest future.
1/27/2012 6:57 AM | Mens Diamond Watches
Gravatar

# Custom Caps

I appreciate your speculating as it attracts people's attention and make this topic discussable.
1/27/2012 6:59 AM | Custom Caps
Gravatar

# Time and Gems

I have been meaning to read this and just never obtained a chance. Its an issue that Im really interested in, I just started reading and Im glad I did. Youre a fantastic blogger, one of the best that Ive seen. This weblog undoubtedly has some facts on topic that I just wasnt aware of. Thanks for bringing this stuff to light.
1/27/2012 7:07 AM | Time and Gems
Gravatar

# eWatches Seiko Watches

I've surfed the net more than three hours today, and your blog was the coolest of all. Thanks a lot, it is really useful to me.
1/27/2012 7:45 AM | eWatches Seiko Watches
Gravatar

# Electric Cigarette

Please tell me that you are going to keep this up! Its so excellent and so important. I cant wait to read a lot more from you. I just feel like you know so significantly and know how to make people listen to what you might have to say. This weblog is just as well cool to become missed. Good stuff, genuinely. Please, PLEASE keep it up!
1/27/2012 8:11 AM | Electric Cigarette
Gravatar

# $%$ WATCH $%$tips for technology

Really informative post. Thanks for sharing
1/28/2012 5:19 AM | tips for technology
Gravatar

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

I was searching for this information. Thanks for sharing this really informative post which is really helpful for me
1/29/2012 1:23 PM | tips for technology
Gravatar

# Cuff Link

This article is so interesting I am completely engrossed. Thanks for a great read.
2/2/2012 1:45 PM | Cuff Link
Gravatar

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

Many people attempt to make their Seo work, nevertheless, they surely should use link submission just because that will get better results.
2/3/2012 6:13 PM | Henderson34Maryann
Gravatar

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

Really informative post indeed. Our Provo insurance agency provides insurance to Provo and also all of Weber county, and also all of Utah! Why go along with just one insurance company when you can assist an independent company that can supply many insurance quotes, not simply info from company. We examine many different plans for people so that you can easily be confident you have the best rates.
Regards
2/4/2012 1:02 PM | provo insurance

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 3 and 8 and type the answer here:

Powered by:
Powered By Subtext Powered By ASP.NET