在ASP.Net MVC中以不同方式设置奇数表行

时间:2010-04-17 11:43:10

标签: .net asp.net asp.net-mvc css

帮我替换这段代码,我和Resharper都不喜欢它:

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

...

</tr>
<%}%>
</table>

4 个答案:

答案 0 :(得分:5)

使用jquery并在客户端上执行 - 您的视图代码将更加清晰。

$(document).ready(function(){
  $("table tr:even").addClass("even");
});

答案 1 :(得分: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>

答案 2 :(得分:1)

Rails有cycle method来执行此操作。

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

答案 3 :(得分:0)

当您在一个屏幕it works better上有多个表时,请使用nth-child。

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