Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is FormCollection in ASP NET MVC?

FormCollection is one way of retrieving view data in controller. Depending on the type of value in input, you can parse its non-string value to string in the Action method.

How do you add value to FormCollection?

FormCollection collection = new FormCollection(); collection. Add("Name", "Value");

What is the use FormCollection class?

Form collection is used to retrieve input elements from the controller action method. Form collection class automatically receives the data form value in controller methods in the form of key/value pair. Key and value pairs are accessed using the key name and index value.


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

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