首页 > 解决方案 > 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 表中的正确产品。

标签: c#asp.net-core.net-coremodel-view-controllerasp.net-core-mvc

解决方案


用 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
}

推荐阅读