2

我想知道在 MVC 3 中是否可以执行以下操作

我基本上有一个带有子集合的 ViewModel,我想使用 Ajax 表单发布它:

模型

    [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; }
    }

销售控制器

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

看法

@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>

基本上我可以将 CustomerVm 的实例发布到控制器,但子集合为空。我正在尝试的甚至可能吗?

4

1 回答 1

2

自己解决了:

看起来视图必须更新为以下内容

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

我还添加了在下拉列表中捕获所选项目的功能

于 2012-04-06T23:08:57.423 回答