c# - Loading items from entity framework created database into dropdownlistfor helper -
i have been struggling loading display list of items database table created through entity framework.
i have found code examples online many have static list of items created , added dropdown list list like. http://www.aspnetmvcninja.com/general/asp-net-mvc-dropdown-list-example. found article scott allen basis have (http://odetocode.com/blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx) think issue im not correctly loading data _jobs?
here code have in controller , other classes, or guidance appreciated feel im close , yet not.
public class jobscontroller : controller { var tasks = db.jobtypes.select(c => new selectlistitem {value = c.jobtypeid.tostring(), text = c.jobdescription}); viewbag.jobtypeallnames = tasks; return view(); }
i have 2 classs being used entity framework code first. job class references jobtypes class.
public class job { [key] [display(name="job id")] public int jobid { get; set; } [display(name = "job type")] public int jobtypesid { get; set; } private readonly list<jobtype> _jobs; public ienumerable<selectlistitem> jobtypeitems { { return new selectlist(_jobs, "jobtypesid", "jobdescription",1); } } } public class jobtype { public int jobtypeid { get; set; } [display(name = "task")] public string jobdescription { get; set; } }
in view have
@html.dropdownlistfor(model => model.jobtypesid, model.jobtypeitems);
this not going compile:
public class jobscontroller : controller { var tasks = db.jobtypes.select(c => new selectlistitem {value = c.jobtypeid.tostring(), text = c.jobdescription}); viewbag.jobtypeallnames = tasks; return view(); }
you need have action return actionresult
, use model have within view rather use viewbag
:
public class jobscontroller : controller { public actionresult index() { var model = new job(); var tasks = db.jobtypes.select(c => new selectlistitem {value = c.jobtypeid.tostring(), text = c.jobdescription}); model.jobtypeitems = tasks; return view(model); } }
ps need adapt job
model include setter , remove un-used _jobs
:
public class job { [key] [display(name="job id")] public int jobid { get; set; } [display(name = "job type")] public int jobtypesid { get; set; } public ienumerable<selectlistitem> jobtypeitems { get; set; } }
Comments
Post a Comment