Question

I have a model:

public class MyModel
{
    public List<Location> Locations { get; set; }
}

Let's say in the list we have 3 items. Then I generate with EditorFor the html for locations:

@Html.EditorFor(a => a.Locations)

The second location was deleted from the html (by javascript I mark the flag for this location as deleted)

In the Action I delete from the list of locations deleted location

model.Locations.RemoveAll(a => a.IsDeleted);

Then I generate the new View with content like this:

@for (int locationIndex = 0; locationIndex < Model.Locations.Count; locationIndex++)
{
    @Html.HiddenFor(m => Model.Locations[locationIndex].Address) <br />
    @Html.HiddenFor(m => Model.Locations[locationIndex].LocationType) <br />
}

Though I CAN'T BELIEVE! When I look on generated html code I see my deleted from the locations list location so I see two locations first and the second. But not first and the third

Please help I have never seen this behavior from MVC. What I am doing wrong?

IMPORTANT UPDATE: Once I replace the @Html.HiddenFor with simple html it works.

    @for (int locationIndex = 0; locationIndex < Model.Locations.Count; locationIndex++)
    {
        <input type="hidden" name="Locations[@locationIndex].Address" value="@Model.Locations[locationIndex].Address" />
        <input type="hidden" name="Locations[@locationIndex].LocationType" value="@Model.Locations[locationIndex].LocationType" />
    }
Was it helpful?

Solution

I've fixed it but replacing Html helper with simple html like this:

 @for (int locationIndex = 0; locationIndex < Model.Locations.Count; locationIndex++)
    {
        <input type="hidden" name="Locations[@locationIndex].Address" value="@Model.Locations[locationIndex].Address" />
        <input type="hidden" name="Locations[@locationIndex].LocationType" value="@Model.Locations[locationIndex].LocationType" />
    }

OTHER TIPS

I was having this exact problem too. After removing an item from my list, previously deleted entries would show up. Your solution solved this for me, thank you.

To help clarify:

@Html.HiddenFor(m => Model[i].id)

Was causing issues, but by creating the html markup manually:

<input type="hidden" name="[@i].Id" value="@Model[i].Id" />

Resulted in the deleted fields remaining deleted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top