Reputation: 317
i have edit view :
<div class="editor-field">
@Html.DropDownList("RoleID", (IEnumerable<SelectListItem>)ViewBag.RoleID, new {class="dropdownlistCustom" })
@Html.ValidationMessageFor(model => model.RoleID)
</div>
controller:
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);
}
}
model:
[Display(Name = "Name Of the Role")]
public int RoleID { get; set; }
[ForeignKey("RoleID")]
public virtual Role Roles { get; set; }
eventhough i set selectedValue
parameter from controller , DropDownList
not showing selected value.
Upvotes: 1
Views: 2308
Reputation: 140
Can pass the value through ViewBag
ViewBag.ReportID = new SelectList(context, "ReportName","ReportName",userdetail.WorkLocation);
@Html.DropDownList("Report", (IEnumerable<SelectListItem>)ViewBag.ReportID })
Upvotes: 2
Reputation: 1571
Better try to set selected option in the datasource itself using 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"]) )
Upvotes: 2