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

6

43

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

Borglum answered 18/4, 2009 at 3:23 Comment(1)
Further how can we find if the item was returned from a text box or a hidden field or a combo box etc?Melly
Z
91

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];
  }
}
Zippel answered 18/4, 2009 at 18:58 Comment(2)
Please note: ToValueProvider() changed between framework 3.5 and 4.0Riba
can i create or Add values to formcollection from model properties in key value pair ?Lianne
A
6
foreach(KeyValuePair<string, ValueProviderResult> kvp in form.ToValueProvider())
{
    string htmlControlName = kvp.Key;
    string htmlControlValue = kvp.Value.AttemptedValue;
}
Arhat answered 20/4, 2009 at 18:48 Comment(1)
This applies to Framework 3.5 where ToValueProvider returns an IDictionary. In Framework 4.0 ToValueProvider returns an IValueProvider.Riba
U
4
foreach(var key in Request.Form.AllKeys)
{
   var value = Request.Form[key];
}
Upbringing answered 18/4, 2009 at 12:46 Comment(0)
V
1

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.

Vitrification answered 5/7, 2012 at 13:52 Comment(0)
R
1

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;
        }
Riba answered 19/4, 2013 at 16:25 Comment(0)
R
0

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
Rai answered 13/8, 2009 at 16:55 Comment(2)
I get "Expression is of type 'System.Web.Mvc.IValueProvider', which is not a collection type" when I try this. If I leave out the "ToValueProvider" it compiles, but I get "Specified cast is not valid."Calore
@Calore - that is because you are using 4.0. This answer applies to 3.5Riba

© 2022 - 2024 — McMap. All rights reserved.