How can a formcollection be enumerated in ASP.NET MVC?

mrblah picture mrblah · Apr 18, 2009 · Viewed 51.9k times · Source

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

Answer

Steve Willcock picture Steve Willcock · Apr 18, 2009

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];
  }
}