In my current project, i faced this problem and couldn't find a quick way to scaffold the Dropdown list of a one-many relation inside one of my Entities.
What I ended up doing was like the following:
1- Create the normal AddView=>Create way.
2- If i had a ID property in my model class, the defaul;t template will generate something like this to represent this property in my view:
<div class="editor-label">
@Html.LabelFor(model => model.CityID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CityID)
@Html.ValidationMessageFor(model => model.CityID)
</div>
3- Now I need to replace this default template with a working one, so I wrote this code in the CREATE
method:
IEnumerable<SelectListItem> cityItems = dataContext.Cities.AsEnumerable().Select(c => new SelectListItem()
{
Text = c.Name,
Value = c.ID.ToString(),
Selected = false,
});
SelectList cityList = new SelectList(cityItems, "Value", "Text");
ViewBag.CityList = cityList;
this will fetch the Cities table and create a Selectlist that i can pass to my view and work with it to provide the DrobDown with it's items.
4- replace the default code in my View by one like the following:
<div class="Post-label">
<div class="editor-label">
@Html.LabelFor(model => model.CityID)
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.CityID, ViewData["CityList"] as SelectList)
@Html.ValidationMessageFor(model => model.CityID)
</div>
</div>
The reason I've used ViewData["CityList"]
instead of ViewBag.CityList
is that this one worked but the other not.
5- now my view is working find and is fetching the City
data just like what I expected, and using the same model inside my Edit
view resulted in a working one too.
Give it a try and let me know what happened, Thanks.