-1

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.

Nate Pet
  • 44,246
  • 124
  • 269
  • 414
  • Does any of them get selected? Forget, does the dropdown have a multiselect property? Is it marking them True? Do you need to invalidate and update the control? Sidenote: Selected will default to false or well it'll reset the value to false, if you just say Selected = (item.CompanyID == 4) – tobeypeters Sep 06 '18 at 16:10
  • @tobeypeters None of them selected. I just have a drop down with all items on the list with the default being "Please Select". It is marking only 1 as true. I double checked. – Nate Pet Sep 06 '18 at 16:23

1 Answers1

0

Try this. In Controller,

var company = _conpanyService.companyLst().ToList();
ViewBag.CompanyList = new SelectList(company, "CompanyId", "CompanyName", 4);

In View,

@Html.DropDownList("CompanyId", (SelectList) ViewBag.CompanyList)
Eric
  • 3,165
  • 1
  • 19
  • 25