【问题标题】:Iterate Through Dictionary Keys and Input Values using Tag Helpers使用标签助手遍历字典键和输入值
【发布时间】:2018-02-27 00:30:36
【问题描述】:

我有一个 asp.net 核心输入表单,它需要遍历具有键类型“产品”和值类型“int”的字典(其中 int 应该是产品的数量)。现在看起来像这样:

@foreach (KeyValuePair<Product, int> product in Model.ProductQuantityDictionary)
{
    <tr>
        <td>
            @product.Key.Name
        </td>
        <td>
            <input asp-for="@product.Value" class="form-control" />
        </td>
    </tr>
}

这成功地显示了产品名称和具有正确默认值 (0) 的输入字段,但是当我提交它时,它实际上并没有提交字典条目。我认为这是因为我只将值而不是 Key 或总 KeyValuePair 输入到字典中,但我不知道该怎么做。我需要为每对现有的键和输入的值做一些事情,更新字典中的条目(字典已经有它需要的所有条目数,我在这里所做的只是更新值)

感谢您的帮助

编辑:这是视图模型。我需要填写该字典,然后将其值传回并根据每对中选择的数量制作产品实例

    public class ProductKit_ViewModel
{
    public int Id { get; set; }
    public int EventId { get; set; }
    public string Name { get; set; }
    public int StyleId { get; set; }
    public Dictionary<Product, int> ProductQuantityDictionary { get; set; }

}

【问题讨论】:

    标签: c# asp.net-core asp.net-core-tag-helpers


    【解决方案1】:

    我认为字典没有默认的标签助手。像这样使用 input asp-for 将无法评估来自 ModelExpression @product.Value 的字段的正确元数据。

    您还会遇到使用“产品”键绑定到字典的问题

    您可以创建自定义标签助手和自定义模型绑定器,但使用默认模型绑定器更简单的解决方法是使用 Dictionary&lt;string, int&gt; 并更改您的视图,如下所示:

    @foreach (var kvp in Model.ProductQuantityDictionary) {
        var name = Html.NameFor(m => m.dict) + "[" + kvp.Key + "]";
        <tr>
            <td>@kvp.Key</td>
            <td><input name="@name" value="@kvp.Value" class="form-control" /></td>
        </tr>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      • 2015-08-07
      • 2017-03-22
      • 1970-01-01
      • 2019-09-05
      相关资源
      最近更新 更多