使用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>
但是当加载视图进行编辑时,dropdownlist始终显示所选的默认/第一项。有人可以帮忙吗?
答案 0 :(得分:1)
在将其传递给视图之前,您是否尝试为列表中的一个元素设置selected = true?
有几个问题,这可能会帮助你喜欢这个:
答案 1 :(得分:-1)
确保模型中的DepartmentId
EditEmployeeModel model = respo.GetEmployeeByID(id);
//model.DepartmentId
不为空,如果您想将--Select Department--
标签显示为@Karthik建议,请尝试
Html.DropDownListFor(m => m.DepartmentId, Model.Departments,"--Select Department")