Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToString() of copied NameValueCollection doesn't output desired results

Tags:

c#

asp.net

I have a NameValueCollection in a usercontrol that is initialized like so:

private NameValueCollection _nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());

When I call the ToString() on this it generates a proper querystring which I can use for an updated url.

However, when I copy the NameValueCollection via its constructor like so:

var nameValues = new NameValueCollection(_nameValues);

And then try to form an url:

var newUrl = String.Concat(_rootPath + "?" + nameValues.ToString());

It outputs an url like this:

"http://www.domain.com?System.Collections.Specialized.NameValueCollection"

How can I copy a NameValueCollection so that the ToString() method outputs desired results?

like image 695
Aage Avatar asked Nov 01 '13 09:11

Aage


Video Answer


1 Answers

The problem is there are two actual types in your code. The fist one is System.Web.HttpValueCollection which has it's ToString method overriden to get the result you expect and the second one is System.Collection.Specialized.NameValueCollection which does not override ToString. What you can do, if you really need to use System.Collection.Specialized.NameValueCollection is to create an extension method.

 public static string ToQueryString(this NameValueCollection collection)
 {
        var array = (from key in collection.AllKeys
                     from value in collection.GetValues(key)
                     select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))).ToArray();
        return "?" + string.Join("&", array);
    }

and use it:

var newUrl = String.Concat(_rootPath,nameValues.ToQueryString());
like image 97
bbeda Avatar answered Sep 22 '22 14:09

bbeda