MVC - Set selected value of SelectList

后端 未结 14 1139
后悔当初
后悔当初 2020-12-13 08:03

How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;

SelectList selectList = new SelectList(items, \"I         


        
相关标签:
14条回答
  • 2020-12-13 09:01

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

    0 讨论(0)
  • 2020-12-13 09:03

    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.

    0 讨论(0)
提交回复
热议问题