asp.net mvc 3 -下拉列表值不与mvc c3 c#设置

本文关键字:mvc c3 设置 下拉列表 net asp | 更新日期: 2023-09-27 18:02:22

使用Asp.net c#, MVC3 Razor视图,我试图在编辑记录时设置下拉列表值,并有以下内容模型:

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>

但是当加载视图进行编辑时,下拉列表总是显示默认的/选中的第一项。有人能帮帮忙吗?

asp.net mvc 3 -下拉列表值不与mvc c3 c#设置

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

有几个问题可能会对你有帮助,比如这个:

  • 下拉列表设置asp.net MVC中的选定项

确保DepartmentId在模型

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

不是空的,如果你想显示一个--Select Department--标签@Karthik建议尝试

Html.DropDownListFor(m => m.DepartmentId, Model.Departments,"--Select Department")