Using FormCollection to take and use each value for any one specific key
I have a bunch of listboxes in the view,开发者_开发百科 each listbox has a unique name/id. When submitted the action method receives the data accordingly that is key = listbox name and value(s) = all selected values for that listbox.
How can I take all values for any one key and perform the desired operation on each value with foreach statement etc.? Looking at the available methods in formcollection they have get(index) and not get(key)...
Thanks...
This should do the trick as well
public ActionResult YourAction(FormCollection oCollection)
{
foreach (var key in oCollection.AllKeys)
{
//var value = oCollection[key];
}
return View();
}
}
or
public ActionResult YourAction(FormCollection oCollection)
{
foreach (var key in oCollection.Keys)
{
//var value = oCollection[key.ToString()];
}
return View();
}
Not sure about this one thou:
public ActionResult YourAction(FormCollection oCollection)
{
foreach (KeyValuePair<int, String> item in oCollection)
{
//item.key
//item.value
}
return View();
}
Ok, this gets the job done. But hoping there's more efficient means to do this?
[HttpPost]
public ActionResult Edit(FormCollection form)
{
var count = form.Count;
int i = 0;
while(i <= count)
{
var ValueCollection = form.Get(i);
var KeyName = form.GetKey(i);
foreach(var value in ValueCollection)
{
//Your logic
}
i++;
}
return View();
}
Probably you are wrong about that there is no Get(key) method, because FormCollection is actually a class derived from NameValueCollection and both it has indexer property which accepts name(or key) and a Get method which accepts name argument.
You can get a key value pair like the one below:
public ActionResult YourAction(FormCollection oCollection)
{
var Item = new List<KeyValuePair<string, string>>();
foreach (var key in oCollection.AllKeys)
{
Item.Add(new KeyValuePair<string, string>(key, oCollection[key]));
}
return View();
}
精彩评论