Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the return value of Request.Form.ToString() different from the result of NameValueCollection.ToString()

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"?

like image 666
Henrik Stenbæk Avatar asked Aug 15 '11 14:08

Henrik Stenbæk


1 Answers

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();
like image 171
dlev Avatar answered Sep 22 '22 23:09

dlev