答案 0 :(得分:1)
I admit, I'm not sure if this answer is quite what you are asking, since I rarely use ViewModels in my app. I'll try to update my answer if I missed the mark.
You can create a SelectList
out of a Model which includes the grouping. In my example, I have a "State/Province" field which is grouped by Country.
So in my Create method of my Controller, I have:
ViewData["StateList"] = new SelectList(_context.Set<State>(), "ID", "Name", "", "CountryID");
Where the paramaters are:
new SelectList(IEnumerable items,
string dataValueField,
string dataTextField,
object selectedValue,
string dataGroupField)
Then my View takes in this SelectList to automatically group elements.
<select class="form-control" style="width: 200px;" asp-for="StateID" asp-items="ViewBag.StateList">
<option>-- Select One --</option>
</select>
Where StateID
is the database field, and ViewBag.StateList
is the equivalent of the ViewData["StateList"]
we created in the controller.