c# - IEnumerable 的使用并且带有隐藏字段和复选框的 foreach 无法将参数从视图传递到控制器
问题描述
我想要实现的是向用户显示一组复选框,其中包含<span>
ProductName 和一个布尔值(如果 ProductName 是否有库存)。我还希望这些复选框可以在同一视图中更新。如果有更新,我想使用主键 ProductKey 更新 SQL 中的表。
我有一个包含以下信息的产品类:
public class Products
{
[Key]
public string ProductKey {get;set;}
public string ProductName {get;set;}
public Boolean IsAvailable {get;set;}
}
实际上,这个问题有点复杂,因为不同的产品可以有不同的属性。为了解决这个问题,我找到了一个创建 IEnumerable 模型的解决方案。这是在对该问题感兴趣的视图之前生成的。
我的问题是我希望能够遍历我的 IEnumerable 模型,查看产品名称是否有库存(指示是否选中了复选框)并能够从同一视图更新可用性。
@model IEnumerable<Products>
<form asp-controller="Product" asp-action="FindIfProductInStock">
<div class="row">
@foreach (var item in Model)
{
<div class="form-group">
<label class="label-checkbox">
<input asp-for=@item.IsAvailable type="checkbox" checked=@item.IsAvailable />
<span>
@Html.DisplayFor(modelItem => item.ProductName)
</span>
</label>
</div>
<div class="form-group">
<input asp-for=@item.ProductKey type="hidden" value=@item.ProductKey />
</div>
}
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</form>
我的FindIfProductInStock
控制器看起来像这样:
[HttpPost]
public IEnumerable<Products> FindIfProductInStock(IEnumerable<Products> productList)
{
return productList;
}
(我现在使用这个控制器能够创建一个断点来查看 productList 的实际值是什么)。
呈现给用户的视图按预期工作。如果产品有库存,则选中复选框。我的问题是 productList 不包含数据。它有 0 行,IsAvailable 为 false,Products 的其余值为 null。有谁知道为什么?
我使用type="hidden"
for ProductKey 因为我不希望用户看到该字段,但我需要它稍后将值连接IsAvailable
到我的 SQL 表中的正确产品。
解决方案
用 for 循环替换 foreach
@for (int i = 0; i < Model.Count; i+=1)
{
.....
<input asp-for=@Model[i].IsAvailable type="checkbox" checked=@Model[i].IsAvailable />
....
@Html.DisplayFor(m => m[i].ProductName)
.... and so on
}
推荐阅读
- react-native - 如何显示 redux 表单渲染中剩余的字符数?
- javascript - 更改日期范围以在 FullCalendar 中显示事件
- javascript - 点击事件刷新我的页面
- html - 角材料模板垫菜单为空
- youtube-api - 来自 Youtube Data API 的结果不一致,使用 Iframe api 播放视频时出现 150 错误代码
- nao-robot - NAOqi:端口 NAO 代码从 2.1 到 2.8
- python - 如何在不指定扩展名的情况下删除文件?
- windows - 在部分已知的文件夹路径下查找文件
- swift - 每次创建新对象时迭代 NSManagedObject 的属性
- javascript - 遍历对象的键,然后遍历值(因为它们是数组)