简体   繁体   English

WebGrid DropDownList所选值?

[英]WebGrid DropDownList Selected Value?

This might be a duplicate question but I couldn't find the solution anywhere. 这可能是一个重复的问题,但我在任何地方都找不到解决方案。 Below is the working code when I use single model object for dropdownlist 以下是我将单个模型对象用于下拉列表时的工作代码

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

The above code works & the selected value is based on the model object ie index for drop down is location id. 上面的代码有效,并且所选值基于模型对象,即下拉列表的索引为位置ID。

However, when I use web grid I'm unable to set the selected value for the dropdownlist like 但是,当我使用网络网格时,无法设置下拉列表的选定值,例如

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

The selected value in the drop down is always with index 1, where as it should be LocationId. 下拉列表中的所选值始终带有索引1,因此应为LocationId。

Is there any way to achieve this functionality? 有什么方法可以实现此功能?

You can add @Html.DropDownList s to grid in foreach like this: 您可以将@Html.DropDownList s添加到foreach 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM