Populating a dropdownlist from a value type
-
14-11-2019 - |
質問
This obviously is pretty basic question but I haven't found my way around this: I'm trying to create a dropdown list for an integer property of my Model, so I can populate the dropdown with a default list of values.
My controller looks like this:
ViewBag.MyListOfOptions = new SelectList(new int[] { 5, 15, 25, 50 });
And my view looks like this:
@Html.DropDownListFor(model => model.MyIntField, new SelectList(ViewBag.MyListOfOptions , [dataValueField], [dataTextField]))
Most examples I've found dataValueField and dataTextField are the properties that should be used in creating the dropdown, but I haven't found a way on how to use DropDownListFor with value types
解決
Because you created the SelectList
from MyListOfOptions
which is already a SelectList
you can use "Text" and "Value"
@Html.DropDownListFor(model => model.MyIntField,
new SelectList(ViewBag.MyListOfOptions , "Value", "Text"))
But you don't need to wrap again an SelectList, so this will also work:
@Html.DropDownListFor(model => model.MyIntField,
(IEnumerable<SelectListItem>)ViewBag.MyListOfOptions)
他のヒント
One easy way to get around this is to take this approach using a ViewModel
: