DropDownList未显示所选值

时间:2013-03-13 10:33:12

标签: asp.net-mvc asp.net-mvc-4 html-select

我有编辑视图:

<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未显示所选值。

2 个答案:

答案 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 })