How do you create a dropdownlist from an enum in ASP.NET MVC? -


i'm trying use html.dropdownlist extension method can't figure out how use enumeration.

let's have enumeration this:

public enum itemtypes {     movie = 1,     game = 2,     book = 3 } 

how go creating dropdown these values using html.dropdownlist extension method?

or best bet create loop , create html elements manually?

for mvc v5.1 use html.enumdropdownlistfor

@html.enumdropdownlistfor(     x => x.yourenumfield,     "select type",      new { @class = "form-control" }) 

for mvc v5 use enumhelper

@html.dropdownlist("mytype",     enumhelper.getselectlist(typeof(mytype)) ,     "select type",     new { @class = "form-control" }) 

for mvc 5 , lower

i rolled rune's answer extension method:

namespace myapp.common {     public static class myextensions{         public static selectlist toselectlist<tenum>(this tenum enumobj)             tenum : struct, icomparable, iformattable, iconvertible         {             var values = tenum e in enum.getvalues(typeof(tenum))                 select new { id = e, name = e.tostring() };             return new selectlist(values, "id", "name", enumobj);         }     } } 

this allows write:

viewdata["taskstatus"] = task.status.toselectlist(); 

by using myapp.common


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -