c# - 将列表中每一项的值提交给控制器(MVC)
问题描述
我正在尝试制作某种购物车,因此我在视图中显示了一个项目列表。
我添加了一个带有“+ Add”值的提交按钮和一个带有显示的每个项目的值金额的数字输入。
这是我的代码:
看法:
@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++)
}
推荐阅读
- python - 迭代多个查询的 Pythonic 方法(并避免使我的代码臃肿)
- javascript - Javascript 异步函数如何在特定点显式产生控制?
- java - Java nio FileChannel 写方法说明
- python - 按存储在字典中的固定宽度切片 DAT 文件
- javascript - JavaScript 按特定常量值对多个属性上的对象数组进行排序
- docusignapi - DocuSign REST API - 检索部分签名的文档
- c - 当我调试 C 程序时,我遇到了这个错误:PreLaunchTask 'C/C++:gcc.exe build active file' 以退出代码 -1 终止
- c - 大小为 1 Valgrind 的无效读取
- c - 检查队列是否为空
- javascript - HTML 文件无法编译