1

使用 Asp.net C#、MVC3 Razor View,我试图在编辑记录时设置下拉列表值并具有以下模型:

public class EditEmployeeModel
    {
        ....
        public int? DepartmentId { get; set; }

        [Required(ErrorMessage = "Department is must")]
        [Display(Name = "Department")]
        public string Department { get; set; }

        public List<SelectListItem> Departments { get; set; }

        .....
}

控制器:

 public ActionResult Edit(string id)
    {
        EditEmployeeModel model = respo.GetEmployeeByID(id);
        model.Departments = GetDepartments();
        return View(model);
    }

并查看:

<div class="editor-field">
@Html.DropDownListFor(m => m.DepartmentId, Model.Departments, new { id ="ddlstDepartments"})
@Html.ValidationMessageFor(m => m.Department)
</div>

但是当视图被加载进行编辑时,下拉列表总是显示默认/第一个选择的项目。有人可以在这里帮忙吗。

4

2 回答 2

1

在将列表中的一个元素传递给视图之前,您是否尝试过设置 selected = true ?

所以有几个问题可能会帮助你喜欢这个:

于 2013-03-06T06:15:58.580 回答
-1

确保DepartmentId在模型

   EditEmployeeModel model = respo.GetEmployeeByID(id);
   //model.DepartmentId

不为空,如果您想--Select Department--按照@Karthik 的建议显示标签,请尝试

Html.DropDownListFor(m => m.DepartmentId, Model.Departments,"--Select Department")
于 2013-03-06T06:17:17.243 回答