WebGrid DropDownList 选定值?

WebGrid DropDownList Selected Value?

这可能是一个重复的问题,但我无法在任何地方找到解决方案。 下面是我对下拉列表使用单个模型对象时的工作代码

    @Html.DropDownListFor(model => model.LocationId, new SelectList(Model.LocationItems, 
                         "Value", "Text",selectedValue: Model.LocationId))

以上代码有效&所选值基于模型对象,即下拉索引是位置 ID。

但是,当我使用网络网格时,我无法像

那样为下拉列表设置选定值
grid.Column(
    header: "Locations",
    format: (item) => @Html.DropDownList("LocationId", Model.First().LocationItems.Select(l => new SelectListItem
    {
        Text = l.Text,
        Value = l.Value,
        Selected = ((WebGridRow)item)["LocationId"].ToString() == l.Value
})))

下拉列表中的所选值始终带有索引 1,而它应该是 LocationId。

有什么方法可以实现这个功能吗?

您可以像这样在 foreach 中将 @Html.DropDownList 添加到 grid

List<WebGridColumn> columns = new List<WebGridColumn>();
foreach (var col in Model)
{
  columns.Add(
  new WebGridColumn()
  {
    header: "Locations",
    Format = (item) => @Html.DropDownList("LocationId", @col.LocationItems.Select(l => new SelectListItem
        {
          Text = l.Text,
          Value = l.Value,
          Selected = ((WebGridRow)item)["LocationId"].ToString() == l.Value
        }
   )});    
}

 @grid.GetHtml(
      columns: columns