Showing posts with label ComboBox. Show all posts
Showing posts with label ComboBox. Show all posts

Tuesday, October 19, 2010

How to set the selected item in an MVC Dropdownlist

The first parameter to the Html.DropDownList needs to be a name that does not match the name in your model. Below I used "OptionId" instead of "Options".

View

<%= Html.DropDownList("OptionId",Model.Options) %>

Controller

SelectListItem item1 = new SelectListItem();

item1.Text = "Red";

item1.Value = "Red";

item1.Selected = false;

viewModel.Options.Add(item1);

SelectListItem item2 = new SelectListItem();

item2.Text = "Green";

item2.Value = "Green";

item2.Selected = true;

viewModel.Options.Add(item2);

SelectListItem item3 = new SelectListItem();

item3.Text = "Blue";

item3.Value = "Blue";

item3.Selected = false;

viewModel.Options.Add(item3);