我有编辑视图:
<div class="editor-field">
@Html.DropDownList("RoleID", (IEnumerable<SelectListItem>)ViewBag.RoleID, new {class="dropdownlistCustom" })
@Html.ValidationMessageFor(model => model.RoleID)
</div>
控制器:
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; }
虽然我从控制器设置selectedValue
参数,但DropDownList
未显示所选值。
答案 0 :(得分:2)
最好尝试使用SelectList
在数据源本身中设置所选选项Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("Value1", "1");
list.Add("Value2", "2");
list.Add("Value3", "3");
var selectList = new SelectList(list,
"Value", "Key",
"2"); // selected item's value "Value2" is selected.
ViewData["SelectedValue"] = selectList;
@Html.DropDownList("ddlValues", (SelectList)ViewData["SelectedValue"]) )
答案 1 :(得分:2)
可以通过ViewBag
ViewBag.ReportID = new SelectList(context, "ReportName","ReportName",userdetail.WorkLocation);
@Html.DropDownList("Report", (IEnumerable<SelectListItem>)ViewBag.ReportID })