c# - Using FormCollection to store values from form -


i have html form page sends data actionresult

the form has 1 x amount of fields based on size of user shopping cart.

<form action="@url.action("addtoshoppingcart","expertestimatorcontroller")" method="post" name="shoppingcart">     <input type="hidden" name="username" value="sampleuser" />     <input type="hidden" name="password" value="badpassword" />      <input type="hidden" name="item1" value="apple">     <input type="hidden" name="quantity1" value="30">      <input type="hidden" name="item2" value="orange">     <input type="hidden" name="quantity2" value="12">      <input type="hidden" name="item3" value="peach">     <input type="hidden" name="quantity3" value="19">      //size varies on shopping cart can 1 item x amount of items </form> 

i want able loop through fields , store them in own variable

i been hard coding , inefficient

    public actionresult addtoshoppingcart(system.web.mvc.formcollection col)     {         string username = col["username"];         string password = col["password"];          string item1= col["item1"];         string qty1 = col["quantity1"];          string item2 = col["item2"];         string qty2 = col["quantity2"];          string item3= col["item3"];         string qty3 = col["quantity3"];          string item4= col["item4"];         string qty4 = col["quantity4"];          // 1 x amount items           return shoppingcartpage();     } 

i tried using

        list<string> list = new list<string>();         foreach (var key in col.asqueryable())         {             list.add(col.get(key.tostring()));         } 

to store each value list can't seem work

essentially trying run through each value , store later

you need this.

list<string> list = new list<string>(); foreach (var key in col.allkeys) {    var value = col[key];    list.add(value); } 

or

foreach (var key in col.keys) {    var value = col[key.tostring()];    list.add(value); } 

Comments