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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With