Myster
Myster

Reputation: 18114

Model Binding to a nested list

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

Action:

[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's first name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter participant's 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 gratefully appreciated.

Cheers.

Murray.

Upvotes: 2

Views: 1804

Answers (1)

veggerby
veggerby

Reputation: 9020

In RTM you deet to ditch the .Index Hidden and your array indexes must be zero-indexed ints

I.e.

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)
        } 
}

Upvotes: 2

Related Questions