user1428798
user1428798

Reputation: 1546

create a combo box dymically fom list in a viewmodel 9+ mvc

I have in my ViewModel a list that contain 2 ou 3 values:

public class person
{
   List<string> civility{get;set;}
   string nom  {get;set;}
   sting prenom  {get;set;}
}

how can i create a combobox in the view mapped to civility property. Sometimes we show combobox if the list contain 2 values et sometimes 3 if the list contains 3 and obtain the value in submit

Upvotes: 0

Views: 1000

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

That's technically as easy as:

@Html.DropDownList("FieldName", Model.civility.Select(m => new SelectListItem { Value = m, Text = m }));

You'll end up with something akin to:

<select id="FieldName" name="FieldName">
    <option value="CivilityItem1">CivilityItem1</option>
    ...
</select>

If you want it tied to an actual property on your model (you'll need to add the property to your model first)

@Html.DropDownListFor(m => m.SelectedCivility, Model.civility.Select(m => new SelectListItem { Value = m, Text = m }))

Upvotes: 1

Related Questions