2010-04-17 52 views
1

幫我將這段代碼,我和ReSharper的不喜歡它:風格奇數錶行

<table width="100%"> 
<% for (int row = 0; row < 10; ++row) {%> 
<%= "<tr" + ((row % 2 == 0) ? " class='even'" : "") + ">" %> 

... 

</tr> 
<%}%> 
</table> 
+0

另一種方式交替: INT倒裝= 0; <%爲(ⅰ... //內^ = 1的循環 倒裝; <%= 「」%> ... <% } %> – 2010-04-18 16:18:26

回答

5

使用jQuery,做在客戶端上 - 您的視圖代碼會這麼幹淨多了。

$(document).ready(function(){ 
    $("table tr:even").addClass("even"); 
}); 
2
public static class TableExtensions 
{ 
    public static string StartRow(this HtmlHelper htmlHelper, int row) 
    { 
     var builder = new TagBuilder("tr"); 
     if (row % 2 == 0) 
     { 
      builder.MergeAttribute("class", "even"); 
     } 
     return builder.ToString(TagRenderMode.StartTag); 
    } 
} 

和:

<table width="100%"> 
<% for (var rowIndex = 0; rowIndex < 10; ++rowIndex) { %> 
    <%= Html.StartRow(rowIndex) %> 
    .... 
    </tr> 
<% } %> 
</table> 

更新:

你可以進一步清理標籤湯:

public static class TableExtensions 
{ 
    private class Row : IDisposable 
    { 
     private readonly TextWriter _writer; 
     private bool _disposed; 

     public Row(ViewContext viewContext) 
     { 
      _writer = viewContext.Writer; 
     } 

     public void Dispose(bool disposing) 
     { 
      if (!_disposed) 
      { 
       _disposed = true; 
       _writer.Write("</tr>"); 
      } 
     } 

     public void Dispose() 
     { 
      this.Dispose(true); 
      GC.SuppressFinalize(this); 
     } 
    } 

    public static IDisposable BeginRow(this HtmlHelper htmlHelper, int rowIndex) 
    { 
     var builder = new TagBuilder("tr"); 
     if (rowIndex % 2 == 0) 
     { 
      builder.MergeAttribute("class", "even"); 
     } 
     htmlHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag)); 
     return new Row(htmlHelper.ViewContext); 
    } 


    public static string StartRow(this HtmlHelper htmlHelper, int row) 
    { 
     var builder = new TagBuilder("tr"); 
     if (row % 2 == 0) 
     { 
      builder.MergeAttribute("class", "even"); 
     } 
     return builder.ToString(TagRenderMode.StartTag); 
    } 
} 

並在視圖:

<table width="100%"> 
<% for (var rowIndex = 0; rowIndex < 10; ++rowIndex) { %> 
    <% using (Html.StartRow(rowIndex)) { %> 
     <td>value 1</td> 
     <td>value 2</td> 
    <% } %> 
<% } %> 
</table> 
+0

不知道這是值得的一次性表我感謝 – ripper234 2010-04-17 12:04:22

+0

然後你需要在行上的自定義屬性和擴展你的幫手......並最終做MvcContrib網格;-) – queen3 2010-04-17 14:12:27

1

Rails有cycle method做到這一點。

菲爾哈克created one到ASP.NET MVC

所以,你可以使用這樣

<style> 
    .first {background-color: #ddd;} 
    .second {background-color: khaki;} 
</style> 

<table> 
<% for (int i = 0; i < 5; i++) { %> 
    <tr class="<%= Html.Cycle("first", "second") %>"> 
     <td>Stuff</td> 
    </tr> 
<% } %> 
</table> 
0

如果在一個屏幕上有多個表格it works better,請使用第n個子項。

$(function() { 
     $('table tr:nth-child(even)').addClass("even"); 
    });