As part of validation I am trying to use a list of values from a dropdown box on the form. When creating a variable like this var form = HttpContext.Current.Request.Form, I can see all the values from the form. In Visual Studio's debugger, the list I'm interested in shows as an array of Text/Value pairs. How can I extract the Values from the form?
1 Answer
Form is already a collection of "Text/Value" pairs. Its type is NameValueCollection, and it stores "Name/Value" pairs. The debugger doesn't make it super easy to navigate since it doesn't show you the values unless you index into it. However, it's very easy to enumerate:
foreach (string key in form.AllKeys)
{
Console.WriteLine("{0} - {1}", key, form[key]);
}
If you don't like not being able to see the values in the debugger windows, you could copy the name/value pairs to a dictionary of key/value pairs first, then inspect the dictionary:
var dictionary = new Dictionary<string, object>();
HttpContext.Current.Request.Form.CopyTo(dictionary);
You can access values by key or iterate this in the same way as above, although there's really no value in converting the original collection to a dictionary if your only gripe is how the debugger displays its contents.
5 Comments
MyFormValue[0].Text MyFormValue[0].Value. How can I extract all the Values from the MyFormValue array?List<>) of just the values with form.AllKeys.Select(k => form[k]).ToList(), or if you're taking the Dictionary approach, dictionary.Values.ToList();.MyFormValue arrayForm object.