首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mvc中的Optgroup

mvc中的Optgroup
EN

Stack Overflow用户
提问于 2018-01-28 15:51:25
回答 1查看 257关注 0票数 0

我的问题是optgroup显示不正确

代码语言:javascript
复制
    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;
    }        
EN

回答 1

Stack Overflow用户

发布于 2018-01-30 07:36:58

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

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

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48484284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档