Question

How can I enumerate through all the key/values of a FormCollection (system.web.mvc) in ASP.NET MVC?

Was it helpful?

Solution

Here are 3 ways to do it specifically with a FormCollection object.

public ActionResult SomeActionMethod(FormCollection formCollection)
{
  foreach (var key in formCollection.AllKeys)
  {
    var value = formCollection[key];
  }

  foreach (var key in formCollection.Keys)
  {
    var value = formCollection[key.ToString()];
  }

  // Using the ValueProvider
  var valueProvider = formCollection.ToValueProvider();
  foreach (var key in valueProvider.Keys)
  {
    var value = valueProvider[key];
  }
}

OTHER TIPS

foreach(KeyValuePair<string, ValueProviderResult> kvp in form.ToValueProvider())
{
    string htmlControlName = kvp.Key;
    string htmlControlValue = kvp.Value.AttemptedValue;
}
foreach(var key in Request.Form.AllKeys)
{
   var value = Request.Form[key];
}

In .NET Framework 4.0, the code to use the ValueProvider is:

        IValueProvider valueProvider = formValues.ToValueProvider();
        foreach (string key in formValues.Keys)
        {
            ValueProviderResult result = valueProvider.GetValue(key);
            string value = result.AttemptedValue;
        }

I use this:

string keyname;
string keyvalue;

for (int i = 0; i <= fc.Count - 1; i++)
{
    keyname = fc.AllKeys[i];
    keyvalue = fc[i];
}

hope it helps someone.

And in VB.Net:

Dim fv As KeyValuePair(Of String, ValueProviderResult)
For Each fv In formValues.ToValueProvider
    Response.Write(fv.Key + ": " + fv.Value.AttemptedValue)
Next
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top