c# - LINQ distinct to @Html.DropDownList -
ok having lot of trouble think should pretty easy. trying populate dropdown list distinct values table.
this linq provides list of departments need each drop down option.
ipacs_master_lists .where (x => (x.department != null)) .select (s => s.department) .distinct () .select (v => v)
how make dropdown list this?
i've tried messing @html.dropdownlist cannot work seems.
my controller follows. tried pass in viewbag couldn't work either.
public actionresult index() { var docs = db.ipacs_master_list; viewbag.departments = new selectlist(db.ipacs_master_list.where(x => (x.department != null)).select (s => s.department).distinct().select (v => v), "id", "department", 0); return view(docs); }
don't use viewbag
, everytime use kitten dies.
seriously, really bad practice.
first, assuming in model:
public class mymodel { public list<documents> docs { get; set; } //don't know type public list<selectlistitem> departments { get; set; } public string department { get; set; } //this holds select in view }
then change action be:
public actionresult index() { mymodel model = new mymodel(); model.docs = db.ipacs_master_list; model.departments = db.ipacs_master_list .where(x => x.department != null) .select(s => s.department) .distinct() .select(s => new selectlistitem { text = s.name, value = s.name }) .tolist(); return view(model); }
then have view use model mymodel
.
then can do:
@html.dropdownlistfor(m => m.department, model.departments)
Comments
Post a Comment