我有如下视图中的 DropDownList,
@Html.DropDownListFor(model => model.RoleID, (IEnumerable<SelectListItem>)ViewBag.RoleID, new { @class = "dropdownlistCustom" })
@Html.DropDownList("RoleID", (IEnumerable<SelectListItem>)ViewBag.RoleID, new { @class = "dropdownlistCustom" })
@Html.ValidationMessageFor(model => model.RoleID)
都试过了DropDownList
,DropDownListFor
都没有正确SelectedValue
。
在 Controller 中,我正在设置selectedValue
参数(请参阅 SelectList() 的最后一个参数)。
public ActionResult Edit(int id = 0)
{
UserDetail userDetail=db.UserDetails.Find(id);
if(userDetail!=null)
{
ViewBag.RoleID = new SelectList(db.Roles.Where(r => r.RoleStatus == "A"), "RoleID", "RoleName", userdetail.RoleID);
return View(userdetail);
}
}
模型 :
[Display(Name = "Name Of the Role")]
public int RoleID { get; set; }
[ForeignKey("RoleID")]
public virtual Role Roles { get; set; }