I’ve been fiddling around with how I could get information from the current content area when in the context of a block controller. First of all, I wanted to know which tag was currently set in the content area. That was reachable through this:
1: var tag = ControllerContext.ParentActionViewContext.ViewData["Tag"] asstring;
Then, I tried getting the actual content area, which I could retrieve by doing this:
1: var currentContentArea = ControllerContext.ParentActionViewContext.ViewData.Model as ContentArea;
By getting the current content area, I could get information on how many items it contained, and what those items were. I could also get the current index of the item. Knowing this, I could control which view to render, based on the current index. In the example below I’ve done just that, with the case being that the blocks rendered first, second and third in the list should have special views.
The code along with the inline comments should be quite self explanatory, but to sum up: The first item in the content area will now be rendered using the First.cshtml view, while item two and three will be rendered using the TwoAndThree.cshtml view (I guess I could have found a better name for that one), while the rest of the views will be rendered with the Index.cshtml view.
And finally: Keep in mind that while I’ve used the currentBlock object in all three views, I could just as well create view models, and populated them only with the data needed in the view. Performance wise, that would probably be a good idea.