需求:在主从表结构中,从表是集合类型,数据在View中通过JS生成,要通过数据绑定传回控制器,在控制器中完成数据存储。
1) View Mode
public class NewOrderView
{
public SaleMain Main { get; set; }
public List<SaleDetail> Details {get; set; }
}
2) View中的引用
View中的集合要实现正确的绑定,要注意两点:
A. 显示在Table中,不能用DisplayFor, 只能用EdiorFor或TextBoxFor,否则不能绑定。
B. 要用带下标的方式表现LIST或Collection,绑定才能正确
m =>m.Details[i].CommodityID
如下面代码中的红色部分,是关键。
@model Store.ViewModels.NewOrderView
<table>
<tr>
<th>
@Html.DisplayNameFor(model =>model.Details.First().CommodityID)
</th>
<th>
@Html.DisplayNameFor(model =>model.Details.First().Quantity)
</th>
<th>
@Html.DisplayNameFor(model =>model.Details.First().PriceUnit)
</th>
<th>
@Html.DisplayNameFor(model =>model.Details.First().Subtotal)
</th>
</tr>
@for (int i = 0; i < Model.Details.Count; i++)
{
<tr>
<td>
@Html.TextBoxFor(m => m.Details[i].CommodityID, null, new { @readonly = true, style= "width: 120px; background-color:#D7EBFF;" })
</td>
<td>
@Html.TextBoxFor(m =>m.Details[i].Quantity, null, new { @readonly = true, style = "width: 50px;background-color:#D7EBFF;" })
</td>
<td>
@Html.TextBoxFor(m => m.Details[i].PriceUnit,null, new { @readonly = true, style = "width: 80px;background-color:#D7EBFF;" })
</td>
<td>
@Html.TextBoxFor(m =>m.Details[i].Subtotal, null, new { @readonly = true, style = "width: 80px;background-color:#D7EBFF;" })
</td>
</tr>
}
</table>
3) 控制器中用法
[HttpPost]
public ActionResult Create(NewOrderView NewOrder, string Add, string Create)
{
….