asp.net mvc - Dropdownlist in Razor MVC 4 -


i want add dropdownlist view few static options without using viewbag, , want bound model. how can this?

well, start writing view model:

public class myviewmodel {     public string selectedvalue { get; set; }     public ienumerable<selectlistitem> values { get; set; } } 

then controller action populate view model , pass view:

public class homecontroller : controller {     public actionresult index()     {         var model = new myviewmodel();          // todo: values coming database or         model.values = new[]         {             new selectlistitem { value = "1", text = "item 1" },             new selectlistitem { value = "2", text = "item 2" },             new selectlistitem { value = "3", text = "item 3" },         };          return view(model);     }      [httppost]     public actionresult index(myviewmodel model)     {         string selectedvalue = model.selectedvalue;         return content("you selected: " + selectedvalue);     } } 

and typed view in use html.dropdownlistfor helper:

@model myviewmodel  @using (html.beginform()) {     @html.dropdownlistfor(x => x.selectedvalue, model.values)     <button type="submit">ok</button> } 

the helper requires 2 parameters: first lambda expression scalar property on view model hold selected value , second ienumerable<selectlistitem> property holding available values displayed in dropdown.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -