Let’s say I want to show multiple Drop Down Boxes each with the same values within them within a View using the @Html.DropDownList.
Is there an easy way to be able to render all of these Drop Down Boxes without having to bind something like the ViewBag to each of the months returned?
For example:
Controller
List<SelectListItem> items = new List<SelectListItem>();
var values = (from v in db.Values select v);
foreach (var value in values)
{
items.Add(new SelectListItem { Text = value.Name, Value = value.Id });
}
ViewBag.Values = PopulateSelectList("Values");
View
@Html.DropDownList("Values")
But what the goal would be is to have something like
<div class="control-group">
@Html.LabelFor(model => model.DesignStyle)
<div class="controls">
@Html.DropDownList("Values") @Html.DropDownList("Values")
@Html.DropDownList("Values") @Html.DropDownList("Values")
@Html.DropDownList("Values") @Html.DropDownList("Values")
@Html.DropDownList("Values") @Html.DropDownList("Values")
@Html.DropDownList("Values") @Html.DropDownList("Values")
</div>
</div>
My guess is I would need some sort of @foreach (item in Model) to populate each of the DropDowns on the View
Here is a sample of my initial thought on how to get something going.
List<SelectListItem> results = new List<SelectListItem>();
SelectListItem item = null;
var values = (from v in db.Values select v);
for (int i = 0; i <= 15; i++)
{
item = new SelectListItem();
item.Text = "Select a value";
item.Value = "1";
results.Add(item);
foreach (var thread in threads)
{
item.Text = thread.Name;
item.Value = thread.Id;
results.Add(item);
}
}
What I don’t want to do is duplicate the logic to populate a SelectListItem multiple times and put each of those in a separate ViewBag item.
I ended up using the EditorTemplate functionality in order to solve / render this.
The Model changed from this:
To this:
Within the
Viewsunder the folder forValue, there is now a sub folder calledEditorTemplates. This contains 2 Views. AValueModel.cshtmland aValueDropDownModel.cshtml.ValueModel.cshtmlcontains:ValueDropDownModel.cshtmlcontains:The
ValueControllernow includes some helper methods to populate the drop downsThe
FillAvailableValuesmethod is called on theCreateActionResultas well as theEditActionResultto initialize the Drop Downs. TheInitDefaultDropDownmethod is called on theCreateActionResultto setup the Drop Downs on the page.