2
\$\begingroup\$

What are your thoughts on using an IDisposable to stripe an HTML table like so? It's a blatant abuse of IDisposable but this allows you to use the counter in a using(){} block which gives you a clear block in the markup.

public class StripeCounter : IDisposable
{
    private string cssClass = "stripe";

    private int counter = 0;

    public StripeCounter(){}

    public StripeCounter(string cssClass)
    {
        this.cssClass = cssClass;
    }

    public MvcHtmlString Stripe()
    {
        return MvcHtmlString.Create(counter++ % 2 == 1 ? cssClass : string.Empty);
    }

    public void Dispose() { }
}

And then the markup

@using (var counter = new StripeCounter())
{
    foreach (var item in Model)
    {
    <tr class="@counter.Stripe()">
        <td>
            ...
        </td>
       ...
    </tr>
    }
}

Regarding comments on using JavaScript to stripe the table:

JavaScript is for behaviour and the striped rows of a table aren't behaviour; they are style, so while it is possible to do so on the client, it seem to me to be something that should be done on the server. For example, if someone has scripts disabled, they would still see the CSS striping, but not JavaScript striping.

\$\endgroup\$
2
  • 3
    \$\begingroup\$ Why are you striping in custom code instead of using jquery (which comes with MVC3)? It is server side work that you can push down to the client. \$\endgroup\$
    – Art Lucia
    Aug 30 '11 at 17:52
  • \$\begingroup\$ This falls into the "Just because you can do something doesn't mean you should" category. Art's comment above is the best response to this. A great option is to do this client side via jQuery or even in plain ole' Javascript. \$\endgroup\$ Aug 30 '11 at 18:30
5
\$\begingroup\$

Don't do the striping on the server. Don't do the striping with JavaScript. Since it's styling, do the striping with CSS.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Note, though, that :nth-child (the CSS pseudo-class that lets you do striping with CSS) doesn't work in IE <9 -- or any other browser that doesn't know CSS3. \$\endgroup\$
    – cHao
    Nov 2 '11 at 15:14
  • 1
    \$\begingroup\$ At that point, you can probably use JavaScript to read the attribute and fake it, though I'm not absolutely sure. Or do it on the server. Or decide that striping is a minor point and it doesn't have to look identical in every browser. \$\endgroup\$ Nov 2 '11 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.