MVC table grid post form and read line by line
asp.net-mvc, forms, grid, post
Solution
You can create a Model for `Stock` and it can be bind to your view. Then you can pass list of stock objects to controller as below.
Stock Model
public class Stock
{
public int StockId { get; set; }
public int Amount { get; set; }
public decimal Price { get; set; }
}
View
@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>
Controllers
public ActionResult ActionStockNew()
{
List<Stock> stockList = new List<Stock>();
// fill stock
return View(stockList);
}
[HttpPost]
public ActionResult ActionStockNew(ICollection<Stock> stockList)
{
// process
}
Thanks!
Problem
I have a table grid (in the web form) and action result. ``` <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 result; ``` [HttpPost] public ActionResult ActionStockNew(FormCollection f) { foreach (var key in f.AllKeys.Where(q => q.StartsWith("f")).ToArray()) { string abba = f[key]; } return View(); } ``` How can read the posted grid data line by line. For example first row data; ``` f[i]StockId f[i]Amount f[i]Price ``` Thanks.