I am having an issue where the item in the dropdown list is not being selected. I am building up an array of SelectListItems and setting the right one to selected = true but its not getting selected.
I have the following code in my controller:
public ActionResult Edit(int id)
{
var p = _myRepository.FindBy(id);
var vm = new MyViewModel(p) { CategoryTypes = ControllerUtils.GetList(_myTypeRepository, r => r.Name, p.CategoryType.Id) };
return View(vm);
}
and here is the GetList function in the ControllerUtils class:
public static class ControllerUtils
{
public static IEnumerable<SelectListItem> GetList<T>(IIntKeyedRepository<T> list, Func<T, string> getName, int id) where T : BaseModel
{
var items = list.All().ToList();
var itemsList = items.Select(r => new SelectListItem() { Selected = r.Id == id, Text = getName(r), Value = r.Id.ToString() });
return itemsList;
}
}
and here is my view code:
<div class="editor-label">
@Html.LabelFor(model => model.MyObject.CategoryType)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.MyObject.CategoryType, Model.CategoryTypes)
@Html.ValidationMessageFor(model => model.MyObject.CategoryType)
</div>
When i debug in the controller code and list into the array of SelectListItem objects i do see the second item has selected = true. But when i check the view HTML, I don’t see either item being selected:
<select id="CategoryType" name="CategoryType">
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
</select>
As you can see, there is no “selected=”selected” for either item. Any suggestions on what could be going on here?
The first argument of the DropDownListFor helper must be a lambda expression pointing to a primitive type property on your view model containing the selected value:
Now get rid of the
Selected = r.Id == idproperty inside yourSelectListItem. You don’t need it. Now assuming thatModel.MyObject.CategoryType.Idhas a corresponding item with matching value insideModel.CategoryTypesthe helper will automatically preselect this item.