【问题标题】:Pass Dictionary<int, string> from View to Controller将 Dictionary<int, string> 从视图传递到控制器
【发布时间】:2020-03-24 02:01:31
【问题描述】:

型号:

public string FreeText { get; set; }
public Dictionary<int, string> SearchValues { get; set; }
public List<DropDownModel> DropDowns { get; set; }

查看:

@using (Html.BeginForm("GetSearchResults", "Home", FormMethod.Post))
{
    @Html.TextBoxFor(m => m.FreeText, new { @class = "form-control mb-3", @placeholder = "Search..." })

    foreach (var dropDown in Model.DropDowns)
    {
        @Html.DropDownListFor(m => m.SearchValues[dropDown.DataFieldId], dropDown.ListItems, dropDown.OptionLabel, new { @class = "form-control mb-3" });
    }

    <button type="submit" class="btn btn-primary btn-block">Search</button>
}

FreeText 输入字段的传递非常好。但即使 SearchValues 字段的下拉列表在页面上正确显示,它在控制器中仍返回为空 (Count = 0)。这是为什么,我可以将字典传递给控制器​​吗?

【问题讨论】:

  • 您正在尝试将下拉字段 ID 保存为 int 并将下拉值保存为字符串是否正确?
  • @JerdineSabio 是的,100% 正确。

标签: asp.net-mvc razor


【解决方案1】:

不使用映射器或更改模型属性的绑定方式,最简单的方法是为您的 SearchValues 创建一个类。

  1. 创建 SearchValue 类
public class SearchValue{
   public int Id {get;set;}
   public string value {get;set;}
}
  1. 将其用作模型中的列表
public string FreeText { get; set; }
// replace dictionary
public List<SearchValue> SearchValues { get; set; }
public List<DropDownModel> DropDowns { get; set; }
  1. 然后使用下面的视图
@using (Html.BeginForm("GetSearchResults", "Home", FormMethod.Post))
{
    @Html.TextBoxFor(m => m.FreeText, new { @class = "form-control mb-3", @placeholder = "Search..." })

    @{
        int counter = 0;
    }
    foreach (var dropDown in Model.DropDowns)
    {
        <input type="hidden" name="SearchValues[@counter].Id" value="@dropdown.DataFieldId">
        @Html.DropDownListFor(m => m.SearchValues[counter].Value, dropDown.ListItems, dropDown.OptionLabel, new { @class = "form-control mb-3" });
        @counter++;
    }

    <button type="submit" class="btn btn-primary btn-block">Search</button>
}

【讨论】:

    【解决方案2】:

    我可以通过将 kvp 从 &lt;int, string&gt; 更改为 &lt;string, string&gt; 来保留字典格式。显然模型绑定器只接受字符串格式的键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-18
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多