2009-04-18 80 views

回答

86

這裏有3種方法可以專門用FormCollection對象來做。

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

請注意:ToValueProvider()框架3.5之間變化和4.0 – Colin 2013-04-19 16:12:11

+0

可以創建或[添加](https://msdn.microsoft.com/en-us/library/system.web.mvc.formcollection.add(V = vs.118)的.aspx)從模型值到`formcollection` [特性](http://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-a-class)在鍵值對中? – stom 2017-01-17 15:34:57

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

這適用於Framework 3.5,其中ToValueProvider返回一個IDictionary。在Framework 4.0中,ToValueProvider返回一個IValueProvider。 – Colin 2013-04-19 16:11:12

0

而且在VB.Net:

Dim fv As KeyValuePair(Of String, ValueProviderResult) 
For Each fv In formValues.ToValueProvider 
    Response.Write(fv.Key + ": " + fv.Value.AttemptedValue) 
Next 
1

我用這個:

string keyname; 
string keyvalue; 

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

希望它可以幫助別人。

1

在.NET Framework 4.0中,使用ValueProvider代碼:

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