WebGrid DropDownList Selected Value?

1.2k Views Asked by At

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 i.e. index for drop down is location 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.

Is there any way to achieve this functionality?

1

There are 1 best solutions below

0
On BEST ANSWER

You can add @Html.DropDownLists to grid in foreach like this:

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