Case: I have a list of items of Class X displayed using Editor Template for Class X.
Problem: How can I get index of an item being processed on the inside of the Editor Template?
Case: I have a list of items of Class X displayed using Editor Template for Class X.
Problem: How can I get index of an item being processed on the inside of the Editor Template?
I've been using this HtmlExtension that returns only the needed id of an iteration. It's basically a regex on
ViewData.TemplateInfo.HtmlFieldPrefix
that's capturing the last number.Can be used in an EditorFor-template like this:
How about:
I think the easiest way is:
Or as helper:
Inspired by @Jona and @Ryan Penfold
Use a for loop instead of for each and pass the indexer into the
EditorFor
extension; razor should handle the rest.Update:
pass in the the index of the item using view data as show above.
In your editor template access the item via the ViewBag
Using the EditorTemplate is the best solution when viewing models that contain a list of something.
In order to find the index for the sub-model being rendered you can use the property that Razor sets by default:
Say, for example, you have the following view models:
and
and you want to be able to edit all the "LineVM" within a "ParagraphVM". Then you would use an Editor Template so you would create a view at the following folder (if it doesn't exist) with the same name as the sub-model
Views/Shared/EditorTemplates/LineVM.cshtml
:Assuming you have a Controller's ActionResult that is returning a View and passing a ParagrapghVM viewmodel to a view, for example
Views/Paragraph/_Paragraph.cshtml
:This view would render as many editors for the list Lines as items contains that list. So if, for example, the property list ParagraphVM.Lines contains 3 items it would render something like:
With that you can know exactly what position each items is within the list and for example use some javascript to create a carousel or whatever you want to do with it. But remember that to edit that list you don't really need to know the position as Razor takes care of it for you. If you post back the model ParagraphVM, the list Lines will have the values bound (if any) without any additional work.
You can use @Html.NameFor(m => m.AnyField). That expression will output the full name property including the index. You could extract the index there...