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?