1

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))
2
  • The problem with List<Object> is that you can't ever reference the properties of each (Object)item value and text. Map these to a list of SelectListItem. Commented Sep 9, 2017 at 18:56
  • Have you tried passing that list of strings to the first overload? Commented Sep 9, 2017 at 19:03

1 Answer 1

3

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.