asp.net-mvc 如何在 ASP.NET MVC 中枚举表单集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/762825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can a formcollection be enumerated in ASP.NET MVC?
提问by mrblah
How can I enumerate through all the key/values of a FormCollection (system.web.mvc) in ASP.NET MVC?
如何枚举ASP.NET MVC 中FormCollection (system.web.mvc) 的所有键/值?
回答by Steve Willcock
Here are 3 ways to do it specifically with a FormCollection object.
以下是使用 FormCollection 对象专门执行此操作的 3 种方法。
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];
}
}
回答by mrblah
foreach(KeyValuePair<string, ValueProviderResult> kvp in form.ToValueProvider())
{
string htmlControlName = kvp.Key;
string htmlControlValue = kvp.Value.AttemptedValue;
}
回答by James Avery
foreach(var key in Request.Form.AllKeys)
{
var value = Request.Form[key];
}
回答by Losbear
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.
希望它可以帮助某人。
回答by Colin
In .NET Framework 4.0, the code to use the ValueProvider is:
在 .NET Framework 4.0 中,使用 ValueProvider 的代码是:
IValueProvider valueProvider = formValues.ToValueProvider();
foreach (string key in formValues.Keys)
{
ValueProviderResult result = valueProvider.GetValue(key);
string value = result.AttemptedValue;
}
回答by Dave
And in VB.Net:
在 VB.Net 中:
Dim fv As KeyValuePair(Of String, ValueProviderResult)
For Each fv In formValues.ToValueProvider
Response.Write(fv.Key + ": " + fv.Value.AttemptedValue)
Next

