TGH
TGH

Reputation: 39258

Submitting form with view model with child collections

I am wondering if the following is possible in MVC 3

I basically have a ViewModel with a child collection that I want to post using an Ajax form:

Model

    [Serializable]
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public int CurrentSalesRep { get; set; }

        public List<SelectListItem> SalesReps { get; set; }
    }

    [Serializable]
    public class CustomerVM
    {
        public List<Customer> Customers { get; set; }
    }

SalesController

        [HttpPost]
        public ActionResult Customers(CustomerVM customer)
        {
            return PartialView(customer);
        }

View

@model  DropdownSave.Models.CustomerVM

<div>
    @{
        using(Ajax.BeginForm("Customers", "Sales", new AjaxOptions { UpdateTargetId = "gridArea",HttpMethod="Post" })){
        <div id="gridArea">
            <table>
            @foreach (var m in Model.Customers)
            {
                <tr>
                    <td>
                        @Html.TextBoxFor(a => m.FirstName)
                    </td>
                    <td>
                        @Html.TextBoxFor(a => m.LastName)
                    </td>
                </tr>
            }
            </table>                   
            <input type="submit" value="Save" /> 

        </div>
        }
     }
</div>

Basically I am able to post an instance of CustomerVm to the controller, but the child collection is null. Is what I'm trying even possible?

Upvotes: 2

Views: 1338

Answers (1)

TGH
TGH

Reputation: 39258

Solved it myself:

Looks like the view has to be updated to the following

<div>
    @{
        using(Ajax.BeginForm("Customers", "Sales", new AjaxOptions { UpdateTargetId = "gridArea",HttpMethod="Post" })){
        <div id="gridArea">
            <table>
            @for (int i = 0; i < Model.Customers.Count; i++)
            {
                <tr>
                    <td>
                        @Html.LabelFor(m => m.Customers[i].FirstName)
                    </td>
                    <td>
                        @Html.LabelFor(m => m.Customers[i].LastName)
                    </td>
                    <td>
                        @Html.HiddenFor(m => m.Customers[i].CurrentSalesRep)
                    </td>
                    <td>
                        @Html.DropDownListFor(m => m.Customers[i].CurrentSalesRep,Model.Customers[i].SalesReps)
                    </td>
                </tr>
            }
            </table>                   
            <input type="submit" value="Save" /> 

        </div>
        }
     }
</div>

I have also added the ability to capture the selected item in the dropdowns

Upvotes: 2

Related Questions