2016-06-20 26 views
0

我有枚舉與值,並使用在DataAnnotations顯示屬性的下拉列表值被正確地示出的顯示屬性,但是從數據庫retreiving數據時它顯示值不使用顯示屬性文本分配DataAnnotations。我如何在我的視圖中獲得顯示值。 我枚舉獲取枚舉顯示值在asp.net MVC視圖

public enum CareerLevel 
     { 
      [Display(Name = "Entry Level")] 
      Level1, 
      [Display(Name = "Experienced Professional")] 
      Level2, 
      [Display(Name = "Department Head")] 
      Level3  
     } 

這裏是我的看法,我想給喜歡 「入門級」 顯示值

@ Html.DisplayFor(modelItem => item.CareerLevel)

它顯示了1級,而不是入門級。我應該在我的視圖或枚舉中做出什麼改變?

+0

可在[這個答案]擴展(http://stackoverflow.com/a/9329279/717088)被用來解決問題了嗎? –

+0

我認爲最乾淨的實現是建立在重複標誌鏈接的新顯示模板格式,這樣,你的看法是遠遠超過調用視圖擴展方法清潔。 – user1666620

+0

Impementing這解決了我的問題,而在視圖中的任何改變http://www.codeproject.com/Articles/776908/Dealing-with-Enum-in-MVC – Fahad

回答

0

您可以創建一個擴展方法來做到這一點;

public static class Extensions 
{ 

public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) 
     where TAttribute : Attribute 
{ 
    return enumValue.GetType() 
        .GetMember(enumValue.ToString()) 
        .First() 
        .GetCustomAttribute<TAttribute>(); 
} 
} 

你可以像這樣使用它;

var level = CareerLevel.Level1 

var name = level.GetAttribute<DisplayAttribute>().Name; 

在你自己的代碼中,你可以使用類似這樣的東西;

@Html.DisplayFor(modelItem => item.CareerLevel.GetAttribute<DisplayAttribute>().Name) 

無論您想使用擴展方法,都必須引用您的擴展類的命名空間。

0

在我的情況下擴展方法使用:

public static class MVCExtentions 
{ 

public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression) 
{ 
    if (expression.Body.NodeType == ExpressionType.Call) 
    { 
     MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body; 
     string name = GetInputName(methodCallExpression); 
     return name.Substring(expression.Parameters[0].Name.Length + 1); 

    } 
    return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1); 
} 

private static string GetInputName(MethodCallExpression expression) 
{ 
    MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression; 
    if (methodCallExpression != null) 
    { 
     return GetInputName(methodCallExpression); 
    } 
    return expression.Object.ToString(); 
} 

public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) where TModel : class 
{ 
    string inputName = GetInputName(expression); 
    var value = htmlHelper.ViewData.Model == null ? default(TProperty): expression.Compile()(htmlHelper.ViewData.Model); 
    return htmlHelper.DropDownList(inputName, ToSelectList(typeof(TProperty), value.ToString())); 
} 
} 

在視圖,然後我用下面的符號:

@Html.EnumDropDownListFor(model => model.CareerLevel, new { @class = "form-control" }) 

我的視圖模型看起來如下:

[EnumDataType(typeof(CareerLevel))] 
[Display(Name = "Level")] 
[DefaultValue(CareerLevel.Level1)] 
public CareerLevel CareerLevelType { get; set; } 

我希望我能不能幫一點...