1

我有编辑视图:

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

4

2 回答 2

2

可以通过值ViewBag

ViewBag.ReportID = new SelectList(context, "ReportName","ReportName",userdetail.WorkLocation);
@Html.DropDownList("Report", (IEnumerable<SelectListItem>)ViewBag.ReportID })
于 2013-04-26T09:46:19.403 回答
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"]) )
于 2013-03-13T11:07:33.670 回答