質問

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:

dropdownlist set selected value in MVC3 Razor

MVC 3 Layout Page, Razor Template, and DropdownList

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top