编辑dropdownList不显示模型的值

时间:2018-09-26 22:46:03

标签: c# asp.net

我想编辑一名雇员,但是在编辑视图中,dropdownList不会显示基于模型的所选项目
控制器:

public ActionResult Edit(int? id)
    {   
        Employee employee = db.tblEmploye.Find(id);
        return View(employee);
    }

edit.cshtml

<div class="form-group">
    @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(Model => Model.Gender, new List<SelectListItem>
               {
                    new SelectListItem{Text = "Male", Value = "Male"},
                    new SelectListItem{Text = "Female", Value = "Female"}
               }, "Select Gender", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

对于要选择的选项,您必须将Selected设置为true。

@Html.DropDownListFor(Model => Model.Gender, new List<SelectListItem>
{
    new SelectListItem{Text = "Male", Value = "Male", Selected = Model.Gender == "Male" },
    new SelectListItem{Text = "Female", Value = "Female", Selected = Model.Gender == "Female" }
}, "Select Gender", new { @class = "form-control" })

SelectList还提供了一些构造函数来使其自动化。

@Html.DropDownListFor(
  model => model.Gender, 
  new SelectList(new [] { "Male", "Female" }, Model.Gender), 
  "Select Gender", 
  new { @class = "form-control" })