List values ​​in a dropdown using ViewData and th viewcode to list it?

How to create a drop-down list using enumeration value in ASP.NET MVC 4?

I have a Language enumeration:

 public enum Language { English = 0, spanish = 2, Arabi = 3 } 

And my property:

 public Language Language { get; set; } 

And my Controller action looks like this:

 [HttpPost] public ActionResult Edit(tList tableSheet) { return RedirectToAction("Index"); } 

How do I call my dropdown list using ViewData[] ?

+4
source share
2 answers

It will return

 Enum.GetNames(typeOf(Language )) English spanish Arabi 

And this one

 Enum.GetValues(typeOf(Language )) 1,2,3 

You can view the list of languages:

 ViewBeg.Languages = Enum.GetNames(typeOf(Language)).ToList(); 
+2
source

I know I'm late for the party, but ... check out the helper class I created to do just that ...

http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23

This steering wheel can be used as follows:

In the controller

 //If you don't have an enum value use the type ViewBag.DropDownList = EnumHelper.SelectListFor<Language>(); //If you do have an enum value use the value (the value will be marked as selected) ViewBag.DropDownList = EnumHelper.SelectListFor(myEnumValue); 

In view

 @Html.DropDownList("DropDownList") 

Assistant:

 public static class EnumHelper { //Creates a SelectList for a nullable enum value public static SelectList SelectListFor<T>(T? selected) where T : struct { return selected == null ? SelectListFor<T>() : SelectListFor(selected.Value); } //Creates a SelectList for an enum type public static SelectList SelectListFor<T>() where T : struct { Type t = typeof (T); if (t.IsEnum) { var values = Enum.GetValues(typeof(T)).Cast<enum>() .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() }); return new SelectList(values, "Id", "Name"); } return null; } //Creates a SelectList for an enum value public static SelectList SelectListFor<T>(T selected) where T : struct { Type t = typeof(T); if (t.IsEnum) { var values = Enum.GetValues(t).Cast<Enum>() .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() }); return new SelectList(values, "Id", "Name", Convert.ToInt32(selected)); } return null; } // Get the value of the description attribute if the // enum has one, otherwise use the value. public static string GetDescription<TEnum>(this TEnum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); if (fi != null) { DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes( typeof(DescriptionAttribute), false); if (attributes.Length > 0) { return attributes[0].Description; } } return value.ToString(); } } 
+1
source

Source: https://habr.com/ru/post/1486778/


All Articles