2016-02-09 25 views
0

我設置了一堆Razor頁面來維護參考表。在數據上下文中的基本結構是這樣的:使用繼承時的MVC/Razor DisplayAttribute

public class RefTableBase { 
    public int Id {get;set;} 
    public string Value {get;set;} 
} 

public class UserType: RefTableBase {} 

public class ReferenceType: RefTableBase {} 

腳手架剃刀頁在那裏正常工作。但是,當我有一個類調用耙表時,頁面不顯示我期望的內容。

public class SomethingImportant { 
    public int Id {get;set;} 
    public string Name {get;set;} 

    public int UserTypeId {get;set;} 
    public virtual UserType UserType {get;set;} 

    public int ReferenceTypeId {get;set;} 
    public virtual ReferenceType ReferenceType {get;set;} 
} 

當index.cshtml頁面腳手架,表頭是這樣的:

@model IEnumerable<Models.SomethingImportant> 

<table class="table"> 
    <tr> 
     <th>@Html.DisplayNameFor(model => model.Id)</th> 
     <th>@Html.DisplayNameFor(model => model.Name)</th> 
     <th>@Html.DisplayNameFor(model => model.UserType.Value)</th> 
     <th>@Html.DisplayNameFor(model => model.ReferenceType.Value)</th> 

但是,當頁面在瀏覽器中實際呈現,列標題顯示

Id Name Value Value 

當我要的是:

Id Name User Type  Reference Type 

我已經嘗試在類中的成員上使用DisplayAttribute,但它沒有奏效。

public class SomethingImportant { 
    // ........... 
    [Display(Name="User Type")] 
    public int UserTypeId {get;set;} 
    public virtual UserType UserType {get;set;} 
    // ........... 
} 

跳過的傳承與實際設置DisplayAttribute爲每個類的派生類之外,還有什麼方法可以讓我得到它顯示我多麼希望?

+1

我將需要'@ Html.DisplayNameFor(型號=> model.UserType)'和'的應用DisplayAttribute'到'UserType'在SomethingImportant –

+0

用戶類型屬性沒有DISPLY屬性 – DanielVorph

+0

只是刪除這些的。價值最後兩行。 (即model.UserType.Value - > model.UserType) –

回答

2

您可以簡單地把對性能的顯示屬性中的問題:

public class SomethingImportant { 
    public int Id {get;set;} 
    public string Name {get;set;} 

    public int UserTypeId {get;set;} 
    [Display(Name="User Type")]//here 
    public virtual UserType UserType {get;set;} 

    public int ReferenceTypeId {get;set;} 
    [Display(Name="Reference Type")]//and here 
    public virtual ReferenceType ReferenceType {get;set;} 
} 

,並刪除調用視圖.Value

<th>@Html.DisplayNameFor(model => model.Id)</th> 
<th>@Html.DisplayNameFor(model => model.Name)</th> 
<th>@Html.DisplayNameFor(model => model.UserType)</th> 
<th>@Html.DisplayNameFor(model => model.ReferenceType)</th> 

如果你需要.Value和它是類的屬性,你可以把Display屬性上的屬性,而不是。

+1

在我嘗試的所有各種組合中...這完美的工作!非常感謝! –