c# - A better way than using ViewBag -
i obtain list of data through docs
has list of every single department , function logged in user has access to. need populate distinct list of departments dropdownlist , distinct list of functions dropdownlist on view page. not using docs
different linq query acheive this. there way can use current model passing?
var docs = (long linq query joins in 4 different tables , returns model) viewbag.departmentlist = db.department.where(x => (x.name != null)).select(s => new selectlistitem { value = s.name, text = s.name }) .distinct(); // fill viewbag unique list of 'department's table. viewbag.functionlist = db.function.where(x => (x.name != null)).select(s => new selectlistitem { value = s.name, text = s.name }) .distinct(); // fill viewbag unique list of 'function's table.
code on view: (strongly typed model)
@model ienumerable<db.models.masterlist> @html.dropdownlist("departmentlist", "select department") @html.dropdownlist("functionlist", "select function")
define model used in view.
public class myviewmodel { public string selecteddepartment { get; set; } public string selectedfunction { get; set; } public ienumerable<selectlistitem> departments { get; set; } public ienumerable<selectlistitem> functions { get; set; } // old model public ienumerable<masterlist> master { get; set;} }
in controller, populate these collections , return model view.
[httpget] public actionresult actionmethodname() { var model = new myviewmodel(); model.departments = db.departments.where(x => (x.name != null)) .select(s => new selectlistitem { value = s.name, text = s.name }) .distinct(); model.functions = db.functions.where(x => (x.name != null)) .select(s => new selectlistitem { value = s.name, text = s.name }) .distinct(); return view(model); }
inside view, use typed html helpers.
@model myviewmodel @html.dropdownlistfor(m => m.selecteddepartment, model.departments) @html.dropdownlistfor(m => m.selectedfunction, model.functions)
when post form server, selecteddepartment
, selectedfunction
should have values selected in view.
Comments
Post a Comment