0

My issue is optgroup is not display properly

enter image description here

    public ActionResult AddMember()
    {          
        ViewBag.ddlEventSelectListItem = GetEventWithNotice();
        return View();
    }

    public List<SelectListItem> GetEventWithNotice()
    {
        List<SelectListItem> ddllst = new List<SelectListItem>();
        DataTable dt = objEN.GetEventWithNoticeList();
        foreach(DataRow dr in dt.Rows)
        {
          ddllst.Add(new SelectListItem { Value = dr["Id"].ToString(), Text= dr["Title"].ToString(), Group=new SelectListGroup { Name=dr["OptGroup"].ToString()}});
        }
        return ddllst;
    }        
  • @using (Html.BeginForm()) {
    @Html.DropDownList("Id", (IEnumerable)ViewBag.ddlEventSelectListItem)
    }
    – Het Tank Jan 28 '18 at 07:52
  • Because your generating a new `SelectListGroup` for each iteration. Refer [this answer](https://stackoverflow.com/questions/37151572/constructing-a-select-list-with-optgroup-groups/37152663#37152663) for the correct usage –  Jan 28 '18 at 07:55

1 Answers1

1

Your current code is generating a new SelectListGroup object for each SelectListItem item you are generating inside your loop. That is why you are seeing one group for each option in the rendered SELECT element.

What you should be doing is, creating unique SelectListGroup objects and use/reuse the corresponding group object for each of theSelectListItems

public List<SelectListItem> GetEventWithNotice()
{
   var dt = objEN.GetEventWithNoticeList();
   // First read the items from data table to a list of anonymous objects
   var items = dt.AsEnumerable().Select(a => new
   {
      Id = a.Field<int>("Id"),
      Title = a.Field<string>("Title"),
      Group = a.Field<string>("OptGroup")
   });
   // Let's get unique Group names and build a dictionary
   // Where the key is the Group name and
   // the value is the SelectListGroup object created from the name
   var groupsDict = items.Select(a => a.Group)
                         .Distinct()
                         .ToDictionary(k => k, y => new SelectListGroup() { Name = y });

   // Let's build the list of SelectListItem's from items 
   // and gets the group from above dictionary
   // while creating each SelectListItem object.

   return items.Select(s => new SelectListItem
   {
       Value = s.Id.ToString(),
       Text = s.Title,
       Group = groupsDict[s.Group]
   }).ToList();
}
Shyju
  • 214,206
  • 104
  • 411
  • 497