How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;
SelectList selectList = new SelectList(items, \"I
The below code solves two problems: 1) dynamically set the selected value of the dropdownlist and 2) more importantly to create a dropdownlistfor for an indexed array in the model. the problem here is that everyone uses one instance of the selectlist which is the ViewBoag.List, while the array needs one Selectlist instance for each dropdownlistfor to be able to set the selected value.
create the ViewBag variable as List (not SelectList) int he controller
//controller code
ViewBag.Role = db.LUT_Role.ToList();
//in the view @Html.DropDownListFor(m => m.Contacts[i].Role, new SelectList(ViewBag.Role,"ID","Role",Model.Contacts[i].Role))
I ended up here because SelectListItem is no longer picking the selected value correctly. To fix it, I changed the usage of EditorFor for a "manual" approach:
<select id="Role" class="form-control">
@foreach (var role in ViewBag.Roles)
{
if (Model.Roles.First().RoleId == role.Value)
{
<option value="@role.Value" selected>@role.Text</option>
}
else
{
<option value="@role.Value">@role.Text</option>
}
}
</select>
Hope it helps someone.