c# - MVC Enitity Framework DropDownListFor<> -
i have searched around site solution , whilst trying numerous methods cant seem working required, follow best mvc best practise creating droplists.
i have 3 models (i have cut them down purposes of this)
model 1 student
public int id {get;set;} public string name {get;set} public site siteid {get;set;}
model 2 site
public int id {get;set;} public string sitename {get;set}
model 3 vm
public int id {get;set} public student students {get;set;} public datetime date { { return datetime.now; } } public bool criteria {get;set;}
in vm view using editorfor html helpers populate vm , student models. site model pre populated @ database seed.
i looking best way include dropdownlist of sites on vm view, map student model.
how correctly set models achieve this?
many in advance, rob
in short, want dropdownlistfor extension method , put list<site>
view model.
here fiddle demonstrates case. fiddle has more details. nuts , bolts here:
viewmodel - add list<site>
public class myviewmodel { public myviewmodel() { this.sites = new list<site>(); } public int id { get; set;} public student students { get; set; } public datetime date { { return datetime.now; } } public bool criteria { get; set; } public list<site> sites { get; set; } }
view - use dropdownlistfor
@html.dropdownlistfor(m => m.sites, new selectlist(model.sites, "id", "sitename"))
in psuedo-code, above says
- the
sites
object in model contains properties display. - create new
selectlist
usingsites
object in model. useid
property data value ,sitename
property data text. - create drop down list based on above info.
controller
this passes seeded view model view.
public actionresult index() { var vm = seedfromdatabase(); return view(vm); } private myviewmodel seedfromdatabase() { var vm = new myviewmodel(); vm.sites.add(new site(0, "one")); vm.sites.add(new site(1, "two")); vm.sites.add(new site(2, "three")); return vm; }
Comments
Post a Comment