问题描述
我正在尝试制作某种购物车,所以我在视图中显示项目列表。
我为每个显示的项目添加了一个提交按钮,其值为“ +添加”,并输入了一个数字,其值为金额。
这是我的代码:
查看:
@model MyProject.ViewModel.AddProductsViewModel
@{
Layout = null;
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<table class="table" align="left" style="padding-left:15px">
<tr>
<th>
Product
</th>
</tr>
@foreach (var item in Model.ProductsList)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Descripcion)
</td>
<td>
<input type="hidden" name="ProductId" value="@item.ProductId" />
<input type="number" id="Amount" name="Amount"
min="1" max="30" value="1">
<input type="submit" value="+ Add" class="btn btn-primary" />
</td>
</tr>
}
</table>
}
模型类:
public class AddProductsViewModel
{
...stuff here...
public List<Products> ProductsList { get; set; }
}
我需要我的控制器从单击提交到的项目中获取productId
,但是通过这种方式,我只能获取列表中第一项的ID。我该如何实现?
解决方法
@{int i = 0;}
@foreach (var item in Model.ProductsList)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Descripcion)
</td>
<td>
<input type="hidden" name="ProductsList[@i].ProductId" value="@item.ProductId" />
<input type="number" id="Amount" name="ProductsList[@i].Amount"
min="1" max="30" value="1">
<input type="submit" value="+ Add" class="btn btn-primary" />
</td>
</tr>
@(i++)
}
,
只需在循环中开始如下形式即可解决问题:
@model MyProject.ViewModel.AddProductsViewModel
@{
Layout = null;
}
@Html.AntiForgeryToken()
<table class="table" align="left" style="padding-left:15px">
<tr>
<th>
Product
</th>
</tr>
@foreach (var item in Model.ProductsList)
{
using (Html.BeginForm())
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Descripcion)
</td>
<td>
<input type="hidden" name="ProductId" value="@item.ProductId" />
<input type="number" id="Amount" name="Amount"
min="1" max="30" value="1">
<input type="submit" value="+ Add" class="btn btn-primary" />
</td>
</tr>
}
}
</table>