asp.net MVC - using list of strings in a DropDownL

2019-09-17 09:46发布

问题:

I am trying to use Html.DropDownListFor with the list of strings from a ViewBag.

Basically I got a ViewBag with a list of string like "Adam","Tom","Mike" etc...

I was wandering if it is possible to pass this list in to DropDownListFor where both Value and text are the items from my list.

I wasn't able to use foreach here...

example with hardcode:

@Html.DropDownListFor(model => model.Name, new SelectList(
          new List<Object>{

               new { value = "Adam" , text = "Adam"  },
               new { value = "Tom" , text = "Tom"  },
               new { value = "Mike" , text = "Mike"  },
               new { value = "Jake" , text = "Jake"  },
            },
          "value",
          "text",
           2))

回答1:

You can generate a collection of SelectListItems from the list of strings and use that with DropDownListFor helper method.

var names = new List<string> {"Adam", "Sam"};
ViewBag.Names = names.Select(f => new SelectListItem() {Value = f, Text = f});

and in the view

@Html.DropDownListFor(f=>f.Name, ViewBag.Names as IEnumerable<SelectListItem>, 
                                                                    "select one")