【问题标题】:Using FormCollection to store values from form使用 FormCollection 存储表单中的值
【发布时间】:2017-04-05 17:59:49
【问题描述】:

我有一个向我的 ActionResult 发送数据的 HTML 表单页面

根据用户购物车的大小,表单有 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()));
        }

将每个值存储到一个列表中,但我似乎无法让它工作

基本上我只是想遍历每个值并将其存储以备后用

【问题讨论】:

  • 为什么要使用 FormCollection?为什么不在客户端生成具有正确名称的表单字段,然后利用 MVC 中的模型绑定器为您创建对象?
  • 它是我无法控制的第 3 方应用程序,它发送一个 Html 文件,我必须使用它来填写购物车

标签: c# asp.net forms formcollection


【解决方案1】:

你需要这个。

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2012-05-21
    相关资源
    最近更新 更多