views:

22

answers:

1

Hi,

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 column 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; }
}
A: 

Just put your column headings in there.

    <tr> 
        <th>Name</th> 
        <th>Address</th> 
        <th>City</th> 
        <th>State</th> 
        <th>Zip</th> 
    </tr> 

If you have the column names in your model somewhere (i.e. DisplayName), you can substitute those for the hard-coded column headings.

Robert Harvey
yes that would be the most straight forward way of doing it.But what I am trying to do is to read from the "DisplayName" Attribute of my object's property.
Eatdoku
Ah, I see your edit there. I'll have to give that some thought. But see MVCContrib Grid. I believe it is capable of reading those attributes and creating column headings from them.
Robert Harvey
Also, note that what you are proposing is not of much value unless you can run a loop for the columns as well as the rows. Otherwise, you are tied to the shape of the underlying model, and you might as well hardcode the column headings.
Robert Harvey
I see what you mean.What I am trying to do is to manage one set of display value for an entity's properties. I am trying to see if I can do that with property's attribute. Just to cover all the scenario before moving with that direction.I am sure there are other maybe better way of doing it.
Eatdoku