asp.net mvc - How to create a static dropdown in Razor syntax? -


after hours of looking on google , stack overflow, can not find 1 bloody example of how build totally brain dead simple dropdown list not come database. honestly, having hard time getting head around mvc. can please show me how create this:

<select name="foobardropdown" id="foobardropdown">     <option value="option1" selected>this option 1</option>     <option value="option2">this option 2</option>     <option value="option3">this option 3</option> </select> 

using this:

@html.dropdownlist.... 

i looking all-in-one-line solution... in view. having devil of time syntax.

i think looking for. best though refactor list construction view model or in controller.

@html.dropdownlist("foobardropdown", new list<selectlistitem> {     new selectlistitem{ text="option 1", value = "1" },     new selectlistitem{ text="option 2", value = "2" },     new selectlistitem{ text="option 3", value = "3" },  })  

an example of placing in controller might this:

public actionresult exampleview() {     var list = new list<selectlistitem>     {         new selectlistitem{ text="option 1", value = "1" },         new selectlistitem{ text="option 2", value = "2" },         new selectlistitem{ text="option 3", value = "3", selected = true },     });       viewdata["foorbarlist"] = list;     return view(); } 

and in view:

@html.dropdownlist("foobardropdown", viewdata["list"] list<selectlistitem>) 

if static list might have reuse in other views / controllers, consider putting logic static class of sorts. example:

public static class dropdownlistutility {        public static ienumerable<selectlistitem> getfoobardropdown(object selectedvalue)     {         return new list<selectlistitem>         {             new selectlistitem{ text="option 1", value = "1", selected = "1" == selectedvalue.tostring()},             new selectlistitem{ text="option 2", value = "2", selected = "2" == selectedvalue.tostring()},             new selectlistitem{ text="option 3", value = "3", selected = "3" == selectedvalue.tostring()},         };                  } 

which leaves few different ways of accessing list.

controller example:

public actionresult exampleview() {     var list = dropdownlistutility.getfoobardropdown("2"); //select second option default;     viewdata["foorbarlist"] = list;     return view(); } 

view example:

@html.dropdownlist("foobardropdown", dropdownlistutility.getfoobardropdown("2")) 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -