I'm trying to generate element names using Html.NameFor<>
method, here's my code:
@foreach (var category in Model.Categories)
{
<input type="hidden" name="@Html.NameFor(m=> category.CategoryId)"
value="@category.CategoryId" />
}
The generated item's name
get this value: category.CategoryId
, instead of Categories[i].CategoryId
(where i
refers to the current indexer).
Why isn't it working?
in short, use a for loop instead of a foreach loop (see the answer here). You need to manually index it
MVC Razor view nested foreach's model
EDIT: added sample code
Okay, for collections that inherit from ICollection, try
Another edit: To avoid using the property name, you could do something like
Its inelegant, but it doesn't hardcode the property name.
And then lets take those guys out of the loop
My apologies for not responding earlier. I logged out as I had other things to do. You also may want to do a null check ie, if count > 0, then assign the propname, otherwise skip the whole thing
According to user1778606's answer, I will use the prop. name and indexer separately, like this:
Use
@Html.HiddenFor
and pass in the array indexed expression forCategoryId