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

守給你的承諾、 提交于 2019-11-26 10:21:56

问题


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


回答1:


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



回答2:


foreach(KeyValuePair<string, ValueProviderResult> kvp in form.ToValueProvider())
{
    string htmlControlName = kvp.Key;
    string htmlControlValue = kvp.Value.AttemptedValue;
}



回答3:


foreach(var key in Request.Form.AllKeys)
{
   var value = Request.Form[key];
}



回答4:


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



回答5:


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.




回答6:


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


来源:https://stackoverflow.com/questions/762825/how-can-a-formcollection-be-enumerated-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!