开发者

asp.net mvc display collection in table with header

I just started doing some web development using asp.net mvc2. I am trying to find a way to display a collection of data in my view. Following is a very simple view markup to display the collection as a html table.

my question would be what do people usually do when constructing table from a collection. How to handle the column header? I do have "DisplayName" attribute on all the object's properties and would like to use them as the table's colum开发者_JAVA百科n headers.

thanks,

<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>

and my class look like the following

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; }
}


You can use

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

To display the display name of MyProp1 within a label tag, and

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

To display the value according to it's display template (usually plain text, unless otherwise specified)

Using <%: %> will also automatically encode the resulting MvcString, as apposed to <%= %>, which does not encode it's contents. However, this auto-encoding is restricted to .NET 4.0 environments, and will not work in prior versions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜