Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 851
LaserBeak Avatar asked Sep 26 '11 01:09

LaserBeak


2 Answers

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();               
  }
like image 182
Kevin Cloet Avatar answered Sep 22 '22 03:09

Kevin Cloet


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();
    }
like image 41
LaserBeak Avatar answered Sep 25 '22 03:09

LaserBeak