Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - post multiple complex objects with form

In an ASP.NET MVC application I am trying to submit multiple objects with a single form. I am able to get simple types to post back but am having issues with complex types. I feel like I have mimicked the example provided by Phil Haack in his blog post Model Binding To A List but with no luck. Even going so far as copying his code exactly to no avail.

I am trying to populate the ProjectNum and TaskNum properties of a set of MachineLicenseBillback objects. Unfortunately the IList<MachineLicenseBillback> machinePts always ends up as a null when posted.

What am I missing?

Class

public class MachineLicenseBillback
{
    public MachineLicenseBillback() { }

    public virtual int MachineId { get; set; }
    public virtual string ProjectNum { get; set; }
    public virtual string TaskNum { get; set; }
    public virtual string VerifiedFlag { get; set; }
    public virtual DateTime? RcdChgDateTime { get; set; }
    public virtual string RcdChgAgent { get; set; }
}

Action

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TrueUp(int id, IList<MachineLicenseBillback> machinePts)
{
  // ...
}

Form

<% using (Html.BeginForm("TrueUp", "Home", new { id = Model.Customer.Id },
             FormMethod.Post))
   { %>
<input type="hidden" name="machinePts.Index" value="<%= machine.MachineId %>" />

<input type="text" name="machinePts[<%= machine.MachineId%>].ProjectNum"
  value="<%= machine.MachineLicenseBillback.ProjectNum %>" />

<input type="text" name="machinePts[<%= machine.MachineId %>].TaskNum"
  value="<%= machine.MachineLicenseBillback.TaskNum %>" />

<input type="submit" value="Submit" />
<% } %>
like image 903
ahsteele Avatar asked Nov 06 '22 17:11

ahsteele


1 Answers

The .Index syntax was removed for MVC 1 RTM and reintroduced in MVC 2. For MVC 1, list elements must be numbered sequentially: machinePts[0], machinePts[1], etc.

like image 77
Levi Avatar answered Nov 11 '22 16:11

Levi