Binding a model to a nested list

I have a nested list that I want to accept as a parameter for my action. I used Phil Haack Post as a starting point and it works well with a single list of levels, but when the parameter is more complex it passes me null. (I haven't ventured under the hood of a model binder yet, do I need it for this example?)

Act:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Payment(..., List<AddonParticipants> addonParticipants)
{...}

      

Model:

// this participant information will be added to the basket
// onto the activity which has the matching Guid.
public class AddonParticipants
{
    public string Guid { get; set; }
    public List<ParticipantDetails> Participants { get; set; }
}
public class ParticipantDetails
{
    [Required(ErrorMessage = "Please enter participant first name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter participant last name")]
    public string LastName { get; set; }
}

      

View pseudocode:

foreach (...)
{
    Html.Hidden("addonParticipants.Index", item.Addon.Guid)
    Html.Hidden("addonParticipants["+item.Addon.Guid+"].Guid", item.Addon.Guid)
    for (int i = 0; i < item.Addon.SubQuantity; i++)
    {
        Html.Hidden("addonParticipants[" + item.Addon.Guid + "].Participants.Index", i)
        Html.TextBox("addonParticipants[" + item.Addon.Guid + "].Participants[" + i + "].FirstName", item.Addon.Participants[i].FirstName)
        Html.TextBox("addonParticipants[" + item.Addon.Guid + "].Participants[" + i + "].LastName", item.Addon.Participants[i].LastName)
    } 
}

      

Suggestions are greatly appreciated.

Greetings.

Murray.

+2


source to share


1 answer


In RTM you can turn off .Index Hidden and your array indices must be indexed at index zero

those.



for(int j = 0; j < ...)
{
        var item = items[j]; // or what ever
        Html.Hidden("addonParticipants["+j+"].Guid", item.Addon.Guid)
        for (int i = 0; i < item.Addon.SubQuantity; i++)
        {
                Html.TextBox("addonParticipants[" + j + "].Participants[" + i + "].FirstName", item.Addon.Participants[i].FirstName)
                Html.TextBox("addonParticipants[" + j + "].Participants[" + i + "].LastName", item.Addon.Participants[i].LastName)
        } 
}

      

+2


source







All Articles