I have the following code:
string Keys = string.Join(",",FormValues.AllKeys);
I was trying to play around with the get:
string Values = string.Join(",", FormValues.AllKeys.GetValue());
But of course that doesn't work.
I need something similar to get all the values, but I don't seem to find the appropriate code to do the same.
P.S: I do not want to use a foreach
loop since that beats the purpose of the first line of code.
I'm using Azure DocumentDB as my logging mechanism, hence writing a dynamic object, but you get the gist...
I have a CustomException where I check for a application-set response code.
Additionally, I take the querystring, form data, and the model so that I can see the values passed before and after the model binder.
If its and Ajax call, I return a Json-formatted response. Otherwise, I return a custom error page.
You can try something like the above.
Edit: The other answers may or may not be what you want. They appear simpler, but the results might not be what you are looking for in all circumstances, but then again, they might be (your mileage may vary).
Note that a
NameValueCollection
is not a 1:1 mapping like a dictionary. You can add multiple values for the same key, which is why a function like.GetValues(key)
returns an array, not a single string.If you have a collection where you have added
Retrieving
collection["Alpha"]
yields"1,2"
. Retrievingcollection.GetValues("Alpha")
yields{ "1", "2" }
. Now, it just so happens that you are using a comma to join your values together into a single string, so this disparity is hidden. However, if you were joining on another value, such as an exclamation point, the results of the other answers would beAnd the code here would be
Use the snippet that demonstrates the behavior you prefer.
Following creates a string from URL parameter list.
i.e
would be
Also you can create an extension method:
Usage:
Also you can easily convert
NameValueCollection
to more handyDictionary<string,string>
so:Gives:
As I found using Reflector,
NameValueCollection.AllKeys
internally performs a loop to gather all te keys, so it seems thatc.Cast<string>()
is more preferable.In cases where you have parsed the query string with System.Web.HttpUtility.ParseQueryString(...) you can just use ToString() and you don't have to re-invent the wheel.
Even though result is NameValueCollection, the underlying type is HttpValueCollection which has the necessary ToString() override to build back a query string.