mardi 21 mars 2017

Binding IEnumerable in ViewModel not working

I have a ViewModel - Customer. Within this there is an IEnumerable collection:

public class Tag
    public int TagNo{ get; set; }
    public DateTime CreatedDate { get; set; }

I output a list of tags to the page - along with the scalar customer information - using a foreach:

...output customer info....
<div class="col-md-9">
        foreach (var Tag in Model.Tags)
            @Html.DisplayFor(x => Tag.TagNo);
            <br />

I am attempting to hide the tag list in the page for the model binder so on errors I don't need to hit the database again:

    int[] tagArray = Model.Tags.Select(x => x.TagNo).ToArray();

    for (int i = 0; i < Model.Tags.Count(); i++)
        @Html.Hidden("Tags[" + i + "]", tagArray[i])

This outputs this:

<input id="Tags_0_" name="Tags[0]" type="hidden" value="21111111" />

I have seen various questions on SO saying you can use an array (as above) in a certain format that the model binder will understand for binding lists - eg: Creating HiddenFor IEnumerable<String> in View

However, when the page has an error and I use the debugger to see what has been bound on the post, Although model.tags appears to have 3 elements - they are all empty.

I have also tried this:

@Html.Hidden("Tags[" + i + "].TagNo", tagArray[i])

But the Customer.Tags collection is empty after posting.

What am I doing wrong? How can I hide this list of tags in the page so that the model binder will see it?

Aucun commentaire:

Enregistrer un commentaire