我的问题是optgroup无法正常显示
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;
}
答案 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();
}