It seems like the ToString () in HttpContext.Request.Form is decorated so the result is different from the one returned from ToString() whencalled directly on a NameValueCollection:
NameValueCollection nameValue = Request.Form;
string requestFormString = nameValue.ToString();
NameValueCollection mycollection = new NameValueCollection{{"say","hallo"},{"from", "me"}};
string nameValueString = mycollection.ToString();
return "RequestForm: " + requestFormString + "<br /><br />NameValue: " + nameValueString;
The result is as the following:
RequestForm: say=hallo&from=me
NameValue: System.Collections.Specialized.NameValueCollection
How can I get "string NameValueString = mycollection.ToString();" to return "say=hallo&from=me"?
The reason you don't see the nicely formatted output is because Request.Form
is actually of type System.Web.HttpValueCollection
. This class overrides ToString()
so that it returns the text you want. The standard NameValueCollection
does not override ToString()
, and so you get the output of the object
version.
Without access to the specialized version of the class, you'll need to iterate the collection yourself and build up the string:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mycollection.Count; i++)
{
string curItemStr = string.Format("{0}={1}", mycollection.Keys[i],
mycollection[mycollection.Keys[i]]);
if (i != 0)
sb.Append("&");
sb.Append(curItemStr);
}
string prettyOutput = sb.ToString();
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