2013-06-18 37 views
4

如何使用ASP.NET MVC 4中的枚舉值創建下拉列表?使用ViewData和th viewcode列出它的枚舉值在下拉列表中?

我有一個Language枚舉:

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

我的屬性是:

public Language Language { get; set; } 

我的控制器動作看起來是這樣的:

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

我怎麼會打電話給我使用ViewData[]查看下拉列表?

回答

2

這將返回

Enum.GetNames(typeOf(Language)) 


English 
spanish 
Arabi 

Enum.GetValues(typeOf(Language)) 


1,2,3 

您可以多種語言列表視圖:

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

讓你詳細闡述一下。我的意思是如何使用viewdata傳遞它,並在html中獲取? – JRU

+0

請參閱更新回答 –

+0

謝謝你....................... – JRU

1

我知道我遲到了,但...看看我創建的幫手類做這個...

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

這helpe可以用作如下:

在控制器:

//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); 

在視圖

@Html.DropDownList("DropDownList") 

助手:

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(); 
    } 
} 
+0

您給出的鏈接不會爲我打開。 –

+1

嗯?我只是自己試了一下,似乎工作得很好......你得到了什麼?一個404? – NinjaNye

+1

我得到了「糟糕!谷歌瀏覽器無法找到www.ninjanye.co.uk」。我來自烏克蘭,這可能是一個原因嗎? –

相關問題