asp.net mvc - Populating a SelectList with Parent/Child Tables -
i trying populate html.dropdownlist in mvc. problem i'm having have child table called "odsessiontopics" has foreign key (id) "odsessiontype" table contain headers topics. here models:
public class odsessiontopic { public int id { get; set; } public string description { get; set; } // foreign key public int odsessiontypeid { get; set; } // navigation property public virtual odsessiontype odsessiontype { get; set; } } public class odsessiontype { public int odsessiontypeid { get; set; } public string description { get; set; } // navigation property public virtual icollection<odsessiontopic> odsessiontopics { get; set; } }
i use following code populate viewbag:
viewbag.odsessiontopicid = new selectlist(db.odsessiontopics, "id", "description", "odsessiontypeid", odsession.odsessiontopicid);
here od session topic data:
id description odsessiontypeid --------------------------------------------------- 1 internal marketing 1 2 team development 1 3 department retreat 2 4 community service 2
here od session type data:
odsessiontypeid description ------------------------------------- 1 plan 2 action
these results:
1 internal marketing team development 2 department retreat community services
here results trying achieve:
plans internal marketing team development actions department retreat community services
the view code is
@html.dropdownlist("odsessiontopicid", null, "-- session type --", htmlattributes: new { @class = "form-control" })
basically, it's grabbing odsessiontypeid foreign key in odsessiontopic table , grouping value. need grab description odsessiontype table. possible? both topics , types editable , have crud logic attached them how arrived design in first place.
you can use linq .join()
, project results anonymous object. assuming var topics = db.odsessiontopics;
, var types = db.odsessiontypes;
query be
var query = topic in topics join type in types on topic.odsessiontypeid equals type.odsessiontypeid select new { group = type.description, id = topic.id, description = topic.description };
which output
{ 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" }
and create selectlist
viewbag.odsessiontopicid = new selectlist(query, "id", "description", "group", odsession.odsessiontopicid)
side note: recommend use typed html helpers generate dropdownlist. viewbag
property should not same name property binding to. instead should (say)
viewbag.topiclist = new selectlist(query, "id", "description", "group", null)
and in view
@html.dropdownlistfor(m => m.odsessiontopicid, (selectlist)viewbag.topiclist, "-- session type --", new { @class = "form-control" })
Comments
Post a Comment