How can I enumerate through all the key/values of a FormCollection (system.web.mvc) in ASP.NET MVC?
How can a formcollection be enumerated in ASP.NET MVC?
Asked Answered
Further how can we find if the item was returned from a text box or a hidden field or a combo box etc? –
Melly
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];
}
}
Please note: ToValueProvider() changed between framework 3.5 and 4.0 –
Riba
can i create or Add values to
formcollection
from model properties in key value pair ? –
Lianne foreach(KeyValuePair<string, ValueProviderResult> kvp in form.ToValueProvider())
{
string htmlControlName = kvp.Key;
string htmlControlValue = kvp.Value.AttemptedValue;
}
This applies to Framework 3.5 where ToValueProvider returns an IDictionary. In Framework 4.0 ToValueProvider returns an IValueProvider. –
Riba
foreach(var key in Request.Form.AllKeys)
{
var value = Request.Form[key];
}
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.
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;
}
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
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.5 –
Riba
© 2022 - 2024 — McMap. All rights reserved.