FormCollection is one way of retrieving view data in controller. Depending on the type of value in input, you can parse its non-string value to string in the Action method.
FormCollection collection = new FormCollection(); collection. Add("Name", "Value");
Form collection is used to retrieve input elements from the controller action method. Form collection class automatically receives the data form value in controller methods in the form of key/value pair. Key and value pairs are accessed using the key name and index value.
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];
}
}
foreach(KeyValuePair<string, ValueProviderResult> kvp in form.ToValueProvider())
{
string htmlControlName = kvp.Key;
string htmlControlValue = kvp.Value.AttemptedValue;
}
foreach(var key in Request.Form.AllKeys)
{
var value = Request.Form[key];
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With