A C# Implementation of Ruby On Rails’ Cycle Method for ASP.NET MVC

Again, another thing that I thought should probably be out there, but when I Googled it, was nowhere to be found.

Basically, in Ruby on Rails, if you want to alternate row colors or something like that, the easiest way is to do:


Which will alternate between the two values you feed it. Alternately, you can pass it a name parameter which will allow you to cycle multiple values independently of each other. Since this is very useful, I went ahead and created if as an ASP.NET MVC Html Helper:

    public static class HtmlHelperExtensions
        private static Dictionary _cycles = new Dictionary();

        public static string Cycle(this HtmlHelper helper, string first, string second, string key = "default")
            return _cycles[key] = (_cycles.ContainsKey(key) && _cycles[key] == first) ? second : first;

Then you can use it in the same way as the Rails helper:

    ">Data Here

Edit: My Colleague Matt pointed out this implementation by Phil Haack, which takes an indefinite number of items to cycle through. His uses the HttpContext to store the values, I used a private static variable. Someone did do it – I guess my Google-foo is just lacking.

Posted Wednesday, May 18th, 2011 under .NET, ASP.NET MVC, Code, Ruby on Rails, Software Development.

Leave a Reply