Devin Wall
Devin Wall

Reputation: 180

ASP.NET MVC BeginCollectionItem issue

I am having an issue with the HTML helper BeginCollectionItem. It seems to be binding the item to the view but and changes are not being propagated.

I have a partial view and the model that is bound to it is an IEnumerable. Below is a snippet.

<tbody>
    @foreach (var entry in Model) {
        <tr>
            @using (Html.BeginCollectionItem("EditedEntries")) {
                <td>@entry.Storeid</td>
                <td>@entry.district</td>
                <td>@Html.EditorFor(x => entry.AdjHrs)</td>
            }
        </tr>
    }
</tbody>

If I remove the the foreach it works, however I need to use a foreach because a collection is returned to the partial view from the Ajax call along with the table and its members.

Upvotes: 4

Views: 1965

Answers (2)

user3559349
user3559349

Reputation:

The BeginCollectionItem is designed to work with a partial view. Create one for your model (I'll assume its named MyModel and you name the partial "_MyModel.cshtml")

@model MyModel
<tr>
    @using (Html.BeginCollectionItem("EditedEntries"))
    {
        <td>@Html.DisplayFor(m => m.Storeid)</td>
        <td>@Html.DisplayFor(m => m.district)</td>
        <td>@Html.EditorFor(m => m.AdjHrs)</td>
    }
</tr>

and then in your other partial, replace the foreach loop with

<tbody>
    @foreach (var entry in Model)
    {
        @Html.Partial("_MyModel", entry)
    }
</tbody>

Upvotes: 3

Devin Wall
Devin Wall

Reputation: 180

So I managed to find the cause of the issue. The HTML helper trying to be smart and auto generate the ID and Name of the hidden fields associated with the data.

What was generated

<tr role="row" class="odd">
<input type="hidden" name="EditedEntries.index" autocomplete="off" value="a2a18da0-528f-4b10-92c1-4a8ba7038dde">
    <td class="sorting_1">1</td>
    <td>1</td>
    <td>
        <input data-val="true" data-val-number="The field AdjHrs must be a number." data-val-required="The AdjHrs field is required." 
        id="EditedEntries_a2a18da0-528f-4b10-92c1-4a8ba7038dde__entry_AdjHrs" name="EditedEntries[a2a18da0-528f-4b10-92c1-4a8ba7038dde].entry.AdjHrs" type="text" value="0">
    </td>

What it needed to be

<tr role="row" class="odd">
<input type="hidden" name="EditedEntries.index" autocomplete="off" value="a2a18da0-528f-4b10-92c1-4a8ba7038dde">
    <td class="sorting_1">1</td>
    <td>1</td>
    <td>
        <input data-val="true" data-val-number="The field AdjHrs must be a number." data-val-required="The AdjHrs field is required." 
        id="EditedEntries_a2a18da0-528f-4b10-92c1-4a8ba7038dde_AdjHrs" name="EditedEntries[a2a18da0-528f-4b10-92c1-4a8ba7038dde].AdjHrs" type="text" value="0">
    </td>

So it prefixed the identifier with the variable name of the 'foreach' I may have to just write my own helper. I will post back when I do.

Upvotes: 0

Related Questions