答案 0 :(得分:1)
您可以使用linq .Join()
并将结果投影到匿名对象。假设var topics = db.ODSessionTopics;
和var types = db.ODSessionTypes;
,那么查询将是
var query = from topic in topics
join type in types on topic.ODSessionTypeID equals type.ODSessionTypeID
select new { Group = type.Description, ID = topic.ID, Description = topic.Description };
将输出
{ Group: "Plan", ID: 1, Description: "Internal Marketing" }
{ Group: "Plan", ID: 2, Description: "Team Development" }
{ Group: "Action", ID: 3, Description: "Department Retreat" }
{ Group: "Action", ID: 4, Description: "Community Services" }
并创建SelectList
ViewBag.ODSessionTopicID = new SelectList(query, "ID", "Description", "Group", oDSession.ODSessionTopicID)
附注:建议您使用强类型的html助手来生成下拉列表。您的ViewBag
属性不应与绑定的属性相同。相反应该是(比方说)
ViewBag.TopicList = new SelectList(query, "ID", "Description", "Group", null)
并在视图中
@Html.DropDownListFor(m => m.ODSessionTopicID, (SelectList)ViewBag.TopicList, "-- Session Type --", new { @class = "form-control" })