Wednesday, June 16, 2010

MVC2 table stripping

Simple scripting tip to set an alternate class to each row of a table when rendering the HTML in an MVC2 view.

Here, my view is a typed view and extends system.Web.Mvc.ViewPage


   1:  <table>
   2:        <thead>
   3:          <tr>
   4:            <th>
   5:              Header 1
   6:            </th>
   7:            <th>
   8:              Header 2
   9:            </th>
  10:          </tr>
  11:        </thead>
  12:        <tbody>
  13:          <% 
  14:            var rowClass = "";
  15:            foreach (var item in Model)
  16:            {
  17:              rowClass = string.IsNullOrEmpty(rowClass) 
  18:                          ? "pair" : ""; %>
  19:          <tr class="<%= Html.Encode(rowClass) %>">
  20:            <td>
  21:              <%= Html.Encode(item.Name) %>
  22:            </td>
  23:            <td>
  24:              <%= Html.Encode(item.Firstname) %>
  25:            </td>
  26:          </tr>
  27:          <% } %>
  28:        </tbody>
  29:      </table>

14: There is a private rowClass variable defined as an empty string outside of the foreach loop
17-18: The rowClass variable is alternatively set to "pair" or "" according to its previous value
19: The value of rowClass is rendered as the 's class attribute values

Of course there must be a "pair" class defined in the css.

0 comments: