【问题标题】:MVC table grid post form and read line by lineMVC表格网格发布表格并逐行读取
【发布时间】:2014-07-14 18:34:41
【问题描述】:

我有一个表格网格(在网络表单中)和操作结果。

<form action="ActionStockNew" method="post" id="form">
    <table>
       <tr>
          <td><input type="text" name="f[0]StockId" /></td>
          <td><input type="text" name="f[0]Amount" /></td>
          <td><input type="text" name="f[0]Price" /></td>
       </tr> 
       <tr>
          <td><input type="text" name="f[1]StockId" /></td>
          <td><input type="text" name="f[1]Amount" /></td>
          <td><input type="text" name="f[1]Price" /></td>
       </tr> 
       <tr>
          <td><input type="text" name="f[2]StockId" /></td>
          <td><input type="text" name="f[2]Amount" /></td>
          <td><input type="text" name="f[2]Price" /></td>
       </tr> 

       ...
    </table>
</form>

动作结果;

[HttpPost]
public ActionResult ActionStockNew(FormCollection f)
{
   foreach (var key in f.AllKeys.Where(q => q.StartsWith("f")).ToArray())
   {
      string abba = f[key];
   }

   return View();
}

如何逐行读取发布的网格数据。

例如第一行数据;

f[i]StockId
f[i]Amount
f[i]Price

谢谢。

【问题讨论】:

    标签: asp.net-mvc forms post grid


    【解决方案1】:

    您可以为Stock 创建一个模型,它可以绑定到您的视图。然后您可以将库存对象列表传递给控制器​​,如下所示。

    库存模型

    public class Stock
    {
        public int StockId { get; set; }
        public int Amount { get; set; }
        public decimal Price { get; set; }
    }
    

    查看

    @model IEnumerable<Stock>
    <form action="/Controler/ActionStockNew" method="post" id="form">
    <table>
        @for (int i = 0; i < Model.Count(); i++)
        {<tr>
            <td>
                <input type="text" name="[@i].StockId" />
            </td>
            <td>
                <input type="text" name="[@i].Amount" />
            </td>
            <td>
                <input type="text" name="[@i].Price" />
            </td>
        </tr>
        }
    </table>
    <input type="submit" value="Save" />
    </form>
    

    控制器

    public ActionResult ActionStockNew()
    {
        List<Stock> stockList = new List<Stock>();
        // fill stock
    
        return View(stockList);
    }
    
    [HttpPost]
    public ActionResult ActionStockNew(ICollection<Stock> stockList)
    {
        // process
    }
    

    谢谢!

    【讨论】:

    • 您好,感谢您的回复。这可以通过表单收集吗?我不想创建库存模型。谢谢。
    • 要按行索引获取数据吗?
    • 可以逐行获取数据,没有库存模型。
    • 您在寻找f["f[0]StockId"]f["f[0]Amount"]f["f[0]Price"] 吗?同样,您可以获得第二行和第三行的值。
    • 是的,大约。但是在 for 循环中 f["f["+i+"]StockId"] ... 其实模型方法要干净得多。
    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 2013-04-24
    • 1970-01-01
    相关资源
    最近更新 更多