In my ASP.NET MVC application, I have a drop-down list in a form on a page, where the dropdown list item that should be selected when the page loads don't get selected.
The ViewModel for the page has a property for the list of SelectListItems that should be used to populate the drop-down list:
See below for the View model and illustration of the "Index" class, which has HeaderItemID as one of it's properties:
public class IndexItemResult
{
public Index FocalIndex { get; set; }
public string FocalIndexHeaderItemText { get; set; }
public List<Item> IndexItems { get; set; }
public List<SelectListItem> ItemSelectList { get; set; }
public List<Item> ItemList { get; set; }
public IndexItemResult() { }
}
public class Index
{
public int IndexID { get; set; }
public string IndexName { get; set; }
public int IndexHeaderItemID { get; set; }
}
I set the "text", "value", and "selected" properties of items in the SelectListItems from a database LINQ query in my controller. This method also sets the "FocalIndex" property of the ViewModel. As HeaderItemID is a property of FocalIndex, I therefore assumed that "HeaderItemID" is available as a field that can be bound to.
"HeaderItemID" is the item that should be selected. When I look at the list of SelectListItems that gets generated, everything looks ok - the "text" and "value" properties are all fine, and the correct item is specified as "selected".
private IndexItemResult GetIndexItemResult(int? indexID)
{
IndexItemResult indexItemResult = new IndexItemResult();
Index focalIndex = db.Indexes.Find(indexID);
indexItemResult.FocalIndex = focalIndex;
int HeaderItemID = focalIndex.IndexHeaderItemID;
indexItemResult.ItemSelectList = db.ItemTexts.
Where(it => it.LanguageID == 1).
Select(iText =>
new SelectListItem
{
Selected =
(
iText.ItemID == HeaderItemID ? true : false
),
Value = iText.ItemID.ToString(),
Text = String.Concat(iText.ID.ToString(), " ", iText.Text)
}).ToList();
return indexItemResult;
}
I then have a form on the page, where I specify the dropdown list with the @Html.DropDownList helper. I pass the list of SelectListItems from the ViewModel in the second parameter.
@Html.DropDownList("IndexHeaderItemID", Model.ItemSelectList,
htmlAttributes: new { @class = "form-control", @id = "HeaderItemDDL" })
The drop-down list renders with all the items as expected, but the item that should be set at "selected" is not selected. Instead, the first item is selected. Any suggestions for what I'm missing here?