Razor element naming convention in foreach loop

I am trying to generate element names using the Html.NameFor<> method, here is my code:

 @foreach (var category in Model.Categories) { <input type="hidden" name="@Html.NameFor(m=> category.CategoryId)" value="@category.CategoryId" /> } 

The generated name element gets this value: category.CategoryId instead of Categories[i].CategoryId (where i refers to the current indexer).

Why doesn't it work?

+1
source share
3 answers

In short, use a for loop instead of a foreach loop (see answer here). You need to manually index it

MVC Razor displays a nested foreach model

EDIT: added sample code

 @for(int i=0; i < Model.ListTwo.Count; i++) { @Html.HiddenFor(t => t.ListTwo[i].Id) } 

Ok, for collections that inherit from ICollection, try

 @for (int i = 0; i < Model.CollectionThree.Count; i++) { @Html.Hidden("CollectionThree[" + i + "].Id", Model.CollectionThree.ElementAt(i).Id) } 

Other editing: To avoid using the property name, you can do something like

 @for (int i = 0; i < Model.CollectionThree.Count; i++) { @Html.Hidden(Html.NameFor(t => Model.CollectionThree) + "[" + i + "]." + Html.NameFor(t =>Model.CollectionThree.ElementAt(i).Id) ,Model.CollectionThree.ElementAt(i).Id ) } 

Its inelegant, but it does not encode the name of the property.

And then take these guys out of the loop

  @{ var collectionname = Html.NameFor(t => Model.CollectionThree); var propname = Html.NameFor(t => Model.CollectionThree.First().Id); } @for (int i = 0; i < Model.CollectionThree.Count; i++) { @Html.Hidden( collectionname+ "[" + i + "]." + propname ,Model.CollectionThree.ElementAt(i).Id ) } 

My apologies for non-compliance earlier. I logged out because I had other things to do. You can also do a null check, i.e., if count> 0, then assign propname, otherwise skip it all

+3
source

According to user1778606 answer , I will use the prop. name and pointer separately, for example:

 @{ var modelName = Html.NameFor(m => m.Categories); var catIndex = 0; } @foreach (var category in Model.Categories) { <input type="hidden" class="checkbox" name="@string.Format("{0}[{1}]", modelName, catIndex++)" value="@category.CategoryId" /> } 
+1
source

Use @Html.HiddenFor and pass in an indexed array expression for CategoryId

 @for(int i=0; i < Model.Categories.Count; i++) { @Html.HiddenFor(m => Model.Categories[i].CategoryId) } 
0
source

All Articles