I have the following code in my controller. Note that if the companyId is 4, I like that to be the default in my dropdownlist:
var company = _conpanyService.companyLst().ToList();
var items = new List<SelectListItem>();
foreach (var item in company)
{
items.Add(new SelectListItem()
{
Text = item.CompanyName,
Value = item.CompanyID.ToString(),
Selected = item.CompanyID == 4 ? true : false
});
}
// I double checked the items list and it does have companyID of 4 set to Select to true. Not sure why it did not propagate to the view.
ViewBag.CompanyList = items;
Content of view:
@Html.DropDownList("CompanyID", (IEnumerable<SelectListItem>)ViewBag.CompanyList, "Please Select", new { @class = "form-control" })
The issue is that even when I view the source code on the View, the selected does not come through. I am not sure why it is not being selected.