asp.net mvc 4 - What is the best way to create dropdownlists in MVC 4? -


i want know,what best way create dropdownlists in mvc 4? viewbag or approach?

i argue since items variable values within view belong in view model. view model not necessarily items coming out of view.

model:

public class somethingmodel {     public ienumerable<selectlistitem> dropdownitems { get; set; }     public string myselection { get; set; }      public somethingmodel()     {         dropdownitems = new list<selectlistitem>();     } } 

controller:

public actionresult dosomething() {     var model = new somethingmodel();             model.dropdownitems.add(new selectlistitem { text = "mytext", value = "1" });     return view(model) } 

view:

@html.dropdownlistfor(m => m.myselection, model.dropdownitems) 

populate in controller or wherever else appropriate scenario.

alternatively, more flexibility, switch public ienumerable<selectlistitem> public ienumerable<mycustomclass> , do:

@html.dropdownfor(m => m.myselection,     new selectlist(model.dropdownitems, "keyproperty", "valueproperty") 

in case, also, of course, have modify controller action populate model.dropdownitems instances of mycustomclass instead.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -