使用FormCollection存储表单中的值

时间:2017-04-05 17:59:49

标签: c# asp.net forms formcollection

我有一个HTML表单页面,可以将数据发送到我的ActionResult

表单根据用户购物车的大小有1到x个字段。

<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 be 1 item to x amount of items
</form>

我希望能够遍历所有字段并将它们存储在自己的变量

我一直很难编码而且效率很低

    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 to x amount items 

        return ShoppingCartPage();
    }

我尝试使用

        List<string> list = new List<string>();
        foreach (var key in col.AsQueryable())
        {
            list.Add(col.Get(key.ToString()));
        }

将每个值存储到列表中,但我似乎无法将其运行

基本上我只是试图遍历每个值并将其存储起来以供日后使用

1 个答案:

答案 0 :(得分:0)

你需要这个。

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

foreach (var key in col.Keys)
{
   var value = col[key.ToString()];
   list.Add(value);
}