asp.net-mvc - MVC表格网格发布表格并逐行读取

标签 asp.net-mvc forms post grid

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

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

Action 结果;

[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

谢谢。

最佳答案

您可以为Stock创建一个模型,并将其绑定(bind)到您的 View 。然后您可以将库存对象列表传递给 Controller ​​,如下所示。

库存型号

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>

Controller

public ActionResult ActionStockNew()
{
    List<Stock> stockList = new List<Stock>();
    // fill stock

    return View(stockList);
}

[HttpPost]
public ActionResult ActionStockNew(ICollection<Stock> stockList)
{
    // process
}

谢谢!

关于asp.net-mvc - MVC表格网格发布表格并逐行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24743394/

相关文章:

Angular 5模板表单检测表单有效性状态的变化

php - Wordpress 组合查询

c# - ASP.NET MVC - 使用 Automapper 进行映射

asp.net-mvc - asp.net mvc 如何为 html.dropdownlist 添加占位符

c# - 使用 DropdownFor 将 null 作为默认值传递

ruby-on-rails - 自定义来自 ActiveResource 的 URL 命中

jquery - 使用 jQuery post 到 ASP.Net webapi

c# - MVC 4 绑定(bind)到子表列表

java - JSF2.0 : How to write h:form in MyComponent in Java?

javascript - React 多步表单提交和验证