在mvc中的Optgroup

时间:2018-01-28 07:51:25

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-3

我的问题是optgroup无法正常显示

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;
    }        

1 个答案:

答案 0 :(得分:1)

您当前的代码正在为您在循环中生成的每个SelectListGroup项生成一个新的SelectListItem对象。这就是为什么你在渲染的SELECT元素中看到每个选项的一个组。

您应该做的是,创建唯一的SelectListGroup个对象,并为每个SelectListItems使用/重用相应的组对象

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();
}