Reputation: 28555
I have a set of dropdowns which are dynamically added by looping a list:
for (int i = 0; i < Model.WindowGlassItems.Count; i++)
{
@Html.DropDownListFor(gu => gu.WindowGlassItems[i], Model.WindowGlassTypes, "-- Select --", new { @class = "form-control glass-multi-select", id = "Glass" + i })
}
WindowGlassItems is of type List<int?>
The dropdown is not showing the selected item even though this list is set with values
what the issue?
EDIT, currently using this hack, which works but im not happy with, Still would prefer a proper MVC solution if possible
@Html.Hidden("HiddenWindowGlassItems", string.Join(",", Model.WindowGlassItems.Select(s => s.ToString()).ToArray()))
JS:
var glassCSV = $("#HiddenWindowGlassItems").val();
if (glassCSV != null) {
var array = glassCSV.split(',');
for (var i = 0; i < array.length; i++) {
$("#Glass" + i + " option[value='" + array[i] + "']").attr("selected", "selected");
}
}
FYI
The selects have names like this: WindowGlassItems[0]
<select name="WindowGlassItems[0]" id="Glass0" data-val-number="The field Nullable`1 must be a number." data-val="true" class="form-control glass-multi-select"><option value="">-- Select --</option>
<option value="637">Tint</option>
etc...
<select name="WindowGlassItems[1]" id="Glass1" data-val-number="The field Nullable`1 must be a number." data-val="true" class="form-control glass-multi-select"><option value="">-- Select --</option>
<option value="637">Tint</option>
etc...
and so on...
Upvotes: 1
Views: 219
Reputation: 28555
In the end this worked:
(this answer helped: MVC looping in razor, generated dropdownlist not value selected )
for (int i = 0; i < Model.WindowGlassUnitsCount; i++)
{
@Html.DropDownListFor(gu => gu.WindowGlassItems[i],
new SelectList(Model.WindowGlassTypes,"Value","Text", Model.WindowGlassItems[i]),
//Model.WindowGlassTypes,
"-- Select --", new { @class = "form-control glass-multi-select", id = "Glass" + i })
}
Upvotes: 2
Reputation: 540
DropDownListFor
doesn't get the selected Value anywhere. The expression go => go.WindowGlassItems[i]
just specifies the Model-Mapping (Name and Id of the Html-Element get generated here)
for (int i = 0; i < Model.WindowGlassItems.Count; i++)
{
@Html.DropDownListFor(
gu => gu.WindowGlassItems[i], // This is the selected value.
new SelectList(Model.WindowGlassTypes, Model.WindowGlassItems[i])
"-- Select --",
new { @class = "form-control glass-multi-select", id = "Glass" + i })
}
pass the selected value with new SelectList()
Upvotes: 2
Reputation: 3254
If you want to have pre selected item, your Model.WindowGlassTypes collection must be of type IList. System.Web.Mvc.SelectListItem has a boolean property Selected, that you will need to set to true to an element that you want to be selected.
Upvotes: 0