I have a Razor view that iterates over a collection property on the view model, and a display template for a single item on that collection. In that single item, I then do the same thing again, so that under the hood I have nested loops that render instances of the same type a number of times on the page.
In the display template for the leaf type, I'd like to find out how many similar items have already been rendered to the page.
I tried to add a property to the ViewBag
and increment it on each iteration, but that didn't work.
Model
public class FooViewModel
{
public IEnumerable<Bar> Bars { get; set; }
}
public class BarViewModel
{
public IEnumerable<Baz> Bazes { get; set; } // how do you pluralize baz?
}
public class BazViewModel
{
}
Index.cshtml
@model FooViewModel
@{
ViewBag.RenderCount = 0;
}
@Html.DisplayFor(m => m.Bars);
DisplayTemplates/BarViewModel.cshtml
@model BarViewModel
@Html.DisplayFor(m => m.Bazes);
DisplayTemplates/BazViewModel.cshtml
@model BazViewModel
// how many BazViewModels have been rendered before this one?
@ViewBag.RenderCount // is 0 every time
@{
ViewBag.RenderCount++;
}