2009-07-10 13 views
55

Wyobraźmy mam wyliczenie takich jak ten (tylko jako przykład):Jak zdobyć wartości wyliczenia w SelectList

public enum Direction{ 
    Horizontal = 0, 
    Vertical = 1, 
    Diagonal = 2 
} 

Jak mogę napisać procedurę, aby te wartości do systemu. Web.Mvc.SelectList, biorąc pod uwagę, że zawartość wyliczenia może ulec zmianie w przyszłości? Chcę dostać każdą nazwę wyliczeń jako tekstu opcji, a jego wartość jako tekst wartości, tak:

<select> 
    <option value="0">Horizontal</option> 
    <option value="1">Vertical</option> 
    <option value="2">Diagonal</option> 
</select> 

To jest najlepsze, co mogę wymyślić do tej pory:

public static SelectList GetDirectionSelectList() 
{ 
    Array values = Enum.GetValues(typeof(Direction)); 
    List<ListItem> items = new List<ListItem>(values.Length); 

    foreach (var i in values) 
    { 
     items.Add(new ListItem 
     { 
      Text = Enum.GetName(typeof(Direction), i), 
      Value = i.ToString() 
     }); 
    } 

    return new SelectList(items); 
} 

jednak zawsze wyświetla tekst opcji jako "System.Web.Mvc.ListItem". Debugowanie przez to również pokazuje mi, że Enum.GetValues ​​() zwraca "poziomy, pionowy" itp. Zamiast 0, 1, jak się spodziewałem, co powoduje, że zastanawiam się, jaka jest różnica między Enum.GetName() i Enum. GetValue().

+1

To jest duży duplikat http://stackoverflow.com/questions/1102022/display-enum-in-combobox-with-spaces i wielu, wielu innych. –

+0

[Wyczerpujące wydania C#] (http://www.codeducky.org/ins-outs-c-enums/) opisuje konwersję między łańcuchami, liczbami i wyliczeniami oraz sposób wyliczenia wartości wyliczeniowych. – ChaseMedallion

Odpowiedz

22

Aby uzyskać wartość enum trzeba rzucić enum do jego podstawowej typu:

Value = ((int)i).ToString(); 
+0

Dzięki! Pomyślałem o tym, ale pomyślałem, że może być sposób, żeby to zrobić bez rzucania. –

73

Minęło trochę czasu odkąd miałem to zrobić, ale myślę, że to powinno działać.

var directions = from Direction d in Enum.GetValues(typeof(Direction)) 
      select new { ID = (int)d, Name = d.ToString() }; 
return new SelectList(directions , "ID", "Name", someSelectedValue); 
+5

Prawie działa, wymaga tylko niewielkiej zmiany! Twój kod ustawi wartość na tekst, gdy OP chce, aby była liczbą całkowitą. Łatwa naprawa. Zmień 'ID = d' na' ID = (int) d'. Dzięki za opublikowanie tego, nigdy bym o tym nie pomyślał! – Chris

+0

Świetna odpowiedź, choć znalazłem, że do wstępnego wypełnienia listy rozwijanej, wartością musiała być reprezentacja tekstowa wyliczenia, a nie liczba całkowita. –

3
nie

może dokładną odpowiedź na pytanie, ale w scenariuszach CRUD zwykle implementuje coś takiego:

private void PopulateViewdata4Selectlists(ImportJob job) 
{ 
    ViewData["Fetcher"] = from ImportFetcher d in Enum.GetValues(typeof(ImportFetcher)) 
           select new SelectListItem 
           { 
            Value = ((int)d).ToString(), 
            Text = d.ToString(), 
            Selected = job.Fetcher == d 
           }; 
} 

PopulateViewdata4Selectlists nazywa się przed widokiem ("Create") i wyświetlania ("Edit"), a następnie w widoku:

<%= Html.DropDownList("Fetcher") %> 

i to wszystko ..

29

jest co właśnie wykonane i osobiście myślę, że jej sexy:

public static IEnumerable<SelectListItem> GetEnumSelectList<T>() 
     { 
      return (Enum.GetValues(typeof(T)).Cast<T>().Select(
       enu => new SelectListItem() { Text = enu.ToString(), Value = enu.ToString() })).ToList(); 
     } 

mam zamiar zrobić kilka rzeczy tłumaczenie ostatecznie więc wartość = enu.ToString() zrobi zawołać coś gdzieś.

+1

Mam problem z tym kodem. "Wartość" SelectList jest taka sama jak "Text". Podczas korzystania z Enums with EntityFramework, wartość zapisana z powrotem do bazy danych musi mieć wartość int. – meffect

+0

Dobrze, zrób to wtedy: Wartość = (int) enu – Dann

+2

(int) enu nie działa –

4

Lub:

foreach (string item in Enum.GetNames(typeof(MyEnum))) 
{ 
    myDropDownList.Items.Add(new ListItem(item, ((int)((MyEnum)Enum.Parse(typeof(MyEnum), item))).ToString())); 
} 
16

chciałem zrobić coś bardzo podobnego do rozwiązania Dann, ale ja potrzebowałem wartość do int i tekst do reprezentacji ciąg wyliczenia. To właśnie wymyśliłem:

public static IEnumerable<SelectListItem> GetEnumSelectList<T>() 
    { 
     return (Enum.GetValues(typeof(T)).Cast<int>().Select(e => new SelectListItem() { Text = Enum.GetName(typeof(T), e), Value = e.ToString() })).ToList(); 
    } 
+0

To zdecydowanie najlepsza odpowiedź. Wartość wymagana do reprezentacji wyliczenia. –

3
public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct 
    { 
     if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj"); 

     var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() }; 
     //var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = e, Name = e.ToString() }; 

     return new SelectList(values, "ID", "Name", enumObj); 
    } 
    public static SelectList ToSelectList<TEnum>(this TEnum enumObj, string selectedValue) where TEnum : struct 
    { 
     if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj"); 

     var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() }; 
     //var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = e, Name = e.ToString() }; 
     if (string.IsNullOrWhiteSpace(selectedValue)) 
     { 
      return new SelectList(values, "ID", "Name", enumObj); 
     } 
     else 
     { 
      return new SelectList(values, "ID", "Name", selectedValue); 
     } 
    } 
4
return 
      Enum 
      .GetNames(typeof(ReceptionNumberType)) 
      .Where(i => (ReceptionNumberType)(Enum.Parse(typeof(ReceptionNumberType), i.ToString())) < ReceptionNumberType.MCI) 
      .Select(i => new 
      { 
       description = i, 
       value = (Enum.Parse(typeof(ReceptionNumberType), i.ToString())) 
      }); 
0

mam więcej klas i metod z różnych powodów:

ENUM do zbierania przedmiotów

public static class EnumHelper 
{ 
    public static List<ItemDto> EnumToCollection<T>() 
    { 
     return (Enum.GetValues(typeof(T)).Cast<int>().Select(
      e => new ItemViewModel 
        { 
         IntKey = e, 
         Value = Enum.GetName(typeof(T), e) 
        })).ToList(); 
    } 
} 

Tworzenie SelectList w kontrolerze

int selectedValue = 1; // resolved from anywhere 
ViewBag.Currency = new SelectList(EnumHelper.EnumToCollection<Currency>(), "Key", "Value", selectedValue); 

MyView.cshtml

@Html.DropDownListFor(x => x.Currency, null, htmlAttributes: new { @class = "form-control" }) 
3

w ASP.NET MVC rdzenia odbywa się to z tag helpers.

<select asp-items="Html.GetEnumSelectList<Direction>()"></select> 
+0

Co to jest dobry sposób w .NET Core –

0

miałem wiele Selectlists enum i po wielu polowań i przesiewania, uznał, że dokonując rodzajowe pomocnika pracował dla mnie najlepsza. Zwraca indeks lub deskryptor jako wartość selectList oraz opis jak tekst selectList:

ENUM:

public enum Your_Enum 
{ 
    [Description("Description 1")] 
    item_one, 
    [Description("Description 2")] 
    item_two 
} 

Helper:

public static class Selectlists 
{ 
    public static SelectList EnumSelectlist<TEnum>(bool indexed = false) where TEnum : struct 
    { 
     return new SelectList(Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(item => new SelectListItem 
     { 
      Text = GetEnumDescription(item as Enum), 
      Value = indexed ? Convert.ToInt32(item).ToString() : item.ToString() 
     }).ToList(), "Value", "Text"); 
    } 

    // NOTE: returns Descriptor if there is no Description 
    private static string GetEnumDescription(Enum value) 
    { 
     FieldInfo fi = value.GetType().GetField(value.ToString()); 
     DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); 
     if (attributes != null && attributes.Length > 0) 
      return attributes[0].Description; 
     else 
      return value.ToString(); 
    } 
} 

Zastosowanie: Ustaw parametr "true" dla indeksów jako wartość:

var descriptorsAsValue = Selectlists.EnumSelectlist<Your_Enum>(); 
var indicesAsValue = Selectlists.EnumSelectlist<Your_Enum>(true); 
Powiązane problemy