c# - Razor DDL to Model -
i trying head around drop down lists mvc, appears failing me. i've been tinkering code shown below can't right.
what trying achieve simple - hard coding drop down options in controller, have them appear in razor rendered html , when option selected, selected value bound string property in model.
with code below can't access li
within view.
i've seen other guides haven't been able make work, binding model best option me, given i'm trying achieve, or viewbag etc better?
could show me i'm going wrong please?
model
public class viewmodel { public string myoption { get; set; } }
view
@model viewmodel @html.dropdownlistfor(m => m.myoption, li, "--select--")
controller
public actionresult index() { list<selectlistitem> li = new list<selectlistitem>(); li.add(new selectlistitem { text = "option one", value = "option1" }); li.add(new selectlistitem { text = "option two", value = "option2" }); return view(li); }
you need pass myoption
view if want use it. valid option creaete view model class containing information need handle on view
viewmodel
public class viewmodel { public ilist<selectlistitem> itemlist {get; set;} public string myoption { get; set; } }
view
@html.dropdownlistfor(m => m.myoption, model.itemlist, "--select--")
controller
public actionresult index() { var li = new list<selectlistitem>(); li.add(new selectlistitem { text = "option one", value = "option1" }); li.add(new selectlistitem { text = "option two", value = "option2" }); var viewmodel = new viewmodel { itemlist = li, myoption = [here code fill this] } return view(viewmodel); }
Comments
Post a Comment