Download the code!
When working in the View of an MVC project, you’ll frequently need to iterate through a list of items. If all you need to do is output the exact same markup for every item, a foreach will serve you well. However, it’s extremely common that you’ll need to generate some sort of alternating sequence for those items, and the foreach quickly turns rather unwieldy ( normally turning into a simpler for loop and having quite a few conditional statements and temporary variables ).
Since I frequently run into the situation that I need to generate alternating ‘templates’ for collections of data, I’ve created a simple Repeater extension to handle the task.
The Repeater Extension
The Repeater is a relatively simple extension, however it does contain the following functionality:
- Works with any enumerable class
- Accepts a string or action to generate markup
- Supports adding custom markup for the beginning & ending of an ‘item’, allowing you to use the same template for both all items.
<div style="width: 100px;">
.BeginTemplate("<div style='border: solid 1px blue;'>")
.BeginAlternatingTemplate("<div style='border: solid 1px red;'>")
<div style="margin: 2px; padding: 4px; border: dashed 1px black;">
<div style="text-align: right;">
<%= item %>
Output from the above example:
While there’s support for a custom alternating template, I’ve found that any style changes you want to make between regular/alternating items can be done through BeginTemplate / BeginAlternatingTemplate.
Using The Repeater In Your Own Project
Download the code first.
The Repeater is contained in the MvcExtensions project. You’ll need to either add the project to your solution or pull out the dll it generates and add then add a reference to the project or dll:
Add a namespace entry to your root web.config namespaces element:
After the reference has been added and the namespace is inserted into the web.config, you should see it show up in auto-complete when writing script code in the view ( might take a bit for autocomplete to recognize the extension):
And you’re ready to go!
If you have any questions or comments, feel free to leave a comment or send me an email!