I’m trying to use the SelectList overload
SelectList(IEnumerable, String, String, Object)
In the controller:
List<MyObj> MyObjList;
MyObj mySel = (from o in MyObjList where o.Name == selectedName select c)
.SingleOrDefault();
// Variant A:
var list = new SelectList(TENANTS, "Code", "Name", (object)(mySel.Name));
// Variant B:
var list = new SelectList(TENANTS, "Code", "Name", (object)(mySel));
ViewBag.ListForDropdown = list;
In the view:
var list = (List<MyObj>)ViewBag.ListForDropdown;
@Html.DropDownListFor(model => model.PropOfTypeMyObject, list, "--- Select One ---")
The DropDownList renders correctly, but no values are selected. I confirmed in the debugger that mySel is an instance from the MyObjList collection.
Is the 4th parameter supposed to be an instance of an object that is in MyObjList? What am I missing to get this to work?
You’re passing in
.Name, which is the Text property of the select list. Use.Codeinstead – the Value property.