Best way to Parse Query String value in Asp.Net


Best way to parse query string value in Asp.Net
//Use it
string cityCode = Request.QueryString.GetValue<string>("City");

//Extension method
        public static T GetValue<T>(this NameValueCollection collection, string key)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }

            var value = collection[key];

            if (value == null)
            {
                throw new ArgumentOutOfRangeException("key");
            }

            var converter = TypeDescriptor.GetConverter(typeof(T));

            if (!converter.CanConvertFrom(typeof(string)))
            {
                throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T)));
            }

            return (T)converter.ConvertFrom(value);
        }
Advertisements
Tagged with: ,
Posted in .Net, Asp.Net, C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Top Rated

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Blog Stats
  • 29,596 hits
%d bloggers like this: