I have this web page which shows the property of an object so that I may edit it, and I populate a DropDownList
with strings coming from another class.
Here's the method I use to populate the DropDownList
:
private void PopulateOBJSetDropdownList(object selectedobj = null)
{
List<string> listOBJSetName = m_OBJSetManager.GetListOBJSets().OrderBy(x => x.m_Name)
.Select(x => x.m_Name.ToString())
.Distinct()
.ToList();
ViewBag.objSetID = new SelectList(listOBJSetName );
}
The ViewBag
property does its job quite well, but the list comes empty when editing the item.
I'm pretty sure it is because of this line:
<div class="editor-label">
@Html.LabelFor(model => model.m_OBJSetID, "Obj Set")
</div>
<div class="editor-field">
@Html.DropDownList("objSetID ", String.Empty)
@Html.ValidationMessageFor(model => model.m_OBJSetID)
</div>
Because the dropdownlist is populated with String.Empty
. This comes from a controller of objs.
Basically, I want this DropDownList
to show me all the names of the objSets available, but I would also want it to have the correct objSet selected by default when editing an obj.
Does anyone can help? Am I clear enough? Thank you everyone.
i would avoid the viewbag. you might want to create a view model, and pass that instead. but this can be done with the viewbag as well.
first, on your view, i would change your dropdown to the following
if you do a view model, you can contain everything this page needs to use in one class, and send it to the view
then on your view, at the top
and you can fill in the drop down like so
hopefully one of those will get you through