MVC Razor Is there a way to populate a DropdownListFor by generating SelectListItems from a List<string> ViewModel

Viewed 42

I am trying to populate a DropDownListFor in my view with SelectListItems generated by a foreach loop iterating through a List of strings in my ViewModel.

Here are attributes I am using in my ViewModel:

public string Selected {get; set;}
public List<string> Strings {get; set;}

Here is my view syntax:

@Html.DropdownListFor(
    model => model.Selected,
    new List<SelectListItem>
    {
        foreach(var answer in Model.Strings)
        {
            new SelectListItem
            {
                Value = answer, Text = answer
            };
        }
    },
    new { htmlAttributes = new { @class = "form-control" } })

Visual studio throws an error under "foreach" that reads:

} expected
) expected
; expected

and another error under the very last ) that reads:

new{
; expected
} expected

I am not sure what I am doing wrong or how to remove these errors. Any advice will be greatly appreciated. Thank you.

1 Answers
List<SelectListItem> item = Model.Strings.ConvertAll(answer =>
                {
                    return new SelectListItem()
                    {
                        Text = answer.ToString(),
                        Value = answer.ToString()
                    };
                });
            
@Html.DropDownListFor(model => model.Selected, item, new { htmlAttributes = new { @class = "form-control" } })
Related