2010-07-02 60 views
4

我剛開始用asp.net mvc2做一些web開發。我試圖找到一種方法在我的視圖中顯示數據集合。以下是一個非常簡單的視圖標記,將集合顯示爲html表格。asp.net mvc display header with header

我的問題是人們通常在從一個集合構造表時做什麼。 如何處理列標題?我在所有對象的屬性上都有「DisplayName」屬性,並希望將它們用作表格的列標題。

感謝,

<table> 
    <thead> 
     <tr> 
      <th>???</th> 
      <th>???</th> 
      <th>???</th> 
      <th>???</th> 
      <th>???</th> 
     </tr> 
    </thead> 
    <tbody> 
    <% 
     foreach(var item in Model) 
     { 
    %> 
     <tr> 
      <td><%= Html.Encode(item.MyProp1)%></td> 
      <td><%= Html.Encode(item.MyProp2)%></td> 
      <td><%= Html.Encode(item.MyProp3)%></td> 
      <td><%= Html.Encode(item.MyProp4)%></td> 
      <td><%= Html.Encode(item.MyProp5)%></td> 
     </tr> 
    <% 
     } 
    %> 
    </tbody> 
</table> 

和我班如下所示

public class MyClass 
{ 
    [DisplayName("Dif Prop 1")] 
    [DataMember] 
    public string MyProp1{ get; set; } 

    [DisplayName("Dif Prop 2")] 
    [DataMember] 
    public string MyProp2{ get; set; } 

    [DisplayName("Dif Prop 3")] 
    [DataMember] 
    public string MyProp3{ get; set; } 

    [DisplayName("Dif Prop 4")] 
    [DataMember] 
    public string MyProp4{ get; set; } 

    [DisplayName("Dif Prop 5")] 
    [DataMember] 
    public string MyProp5{ get; set; } 
} 

回答

0

您可以使用

<%: Html.LabelFor(x => x.MyProp1) %> 

要將標籤標籤中顯示MyProp1的顯示名稱,

<%: Html.DisplayFor(x => x.MyProp1) %> 

要根據它的顯示模板(通常是純文本,除非另有規定)

使用<%顯示該值:%>也會自動進行編碼所得到的MvcString,作爲並列於<%=%>,這不編碼它的內容。但是,此自動編碼僅限於.NET 4.0環境,並且在以前的版本中不起作用。

+1

LabelFor的問題是它將標籤標籤包裹在它的周圍,這不是您想要的表頭中的標籤。 – 2011-07-05 15:16:38