0

There are many questions about this on the site already, but I can't find one that actually replicates or solves my issue.

Given Models like this:

public class Tnc
{
    public virtual Customer Customer { get; set; }

    public int ListTncId { get; set; }
    public int CustomerId { get; set; }
    public bool AcceptsTnc { get; set; }    
}

public class Customer
{
    List<Tnc> Tncs { get; set; }
    // other properties
}

I am rendering them in the View like this:

@for (int i = 0; i < Model.Tncs.Count; i++)
{
    @Html.HiddenFor(model => model.Tncs.ElementAt(i).ListTncId)
    @Html.HiddenFor(model => model.Tncs.ElementAt(i).CustomerId)
    <dd class="checkbox-dd">@Html.EditorFor(model => model.Tncs.ElementAt(i).AcceptsTnc)</dd>
}

But when the customer model is posted back to the controller, the Tncs collection is always empty (has no children, rather than null).

My understanding is that if you included the essential Ids as part of the form, the objects would be reassembled on postback. However, my understanding is obviously wrong. I presume it's connected to the fact that all the resulting hidden fields have the same name and id attributes:

<input id="ListTncId" name="ListTncId" type="hidden" value="6" />
<input id="CustomerId" name="CustomerId" type="hidden" value="23" />                
<dd class="checkbox-dd">
    <input class="check-box" id="AcceptsTnc" name="AcceptsTnc" type="checkbox" value="true" />
</dd>

<input id="ListTncId" name="ListTncId" type="hidden" value="7" />
<input id="CustomerId" name="CustomerId" type="hidden" value="23" />                
<dd class="checkbox-dd">
    <input class="check-box" id="AcceptsTnc" name="AcceptsTnc" type="checkbox" value="true" />
</dd>

Is there any way to reconnect this data when it posts back to the controller?

Bob Tway
  • 9,301
  • 17
  • 80
  • 162
  • 1
    You cannot use `.ElementAt()` - its need to be `@Html.HiddenFor(m => m.Tncs[i].ListTncId)` etc –  Dec 08 '17 at 10:23
  • Just to understand betterr, why are you not using ForEach – ankur Dec 08 '17 at 10:47
  • 1
    @ankur Because you need to supply an index for this to work - it needs the index to correctly populate the name and id values in the HTML elements. – Bob Tway Dec 08 '17 at 10:49

0 Answers0