WebGrid DropDownList选择值?

时间:2017-09-06 15:28:44

标签: c# asp.net-mvc razor dropdown webgrid

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

    @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。

有没有办法实现这个功能?

1 个答案:

答案 0 :(得分:1)

您可以@Html.DropDownListgrid添加到foreach,如下所示:

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
相关问题