从MVC局部视图获取数据

时间:2013-05-20 11:38:04

标签: asp.net-mvc asp.net-mvc-4 razor

我为我的主模型定义了一个视图,并在其中调用了详细的局部视图。我的主模型包含一个列表。当页面回发到服务器时,如何从部分视图中获取数据? 这是我的代码:

OrderModel:

public string ShipName { get; set; }
public string ShipAddress { get; set; }
public IList<OrderDetailModel> OrderDetailModels { get; set; }

OrderDetailModel:

public int OrderID { get; set; }
public int Quantity { get; set; }
public int UnitPrice { get; set; }

public OrderModel OrderModel { get; set; }

订单查看

     @model MvcFirstSample.Models.OrderModel
    @{
        ViewBag.Title = "create";
    }

    <h2>create</h2>

    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)


        //.....

    @Html.Partial("OrderDetail")
}

这是我对OrderDetailView的部分视图:

@model MvcFirstSample.Models.OrderDetailModel
@{
    ViewBag.Title = "OrderDetail";
}
Partial view OrderDetail
<div class="editor-label">
    @Html.LabelFor(model => model.Quantity)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Quantity)
    @Html.ValidationMessageFor(model => model.Quantity)
</div>
<div class="editor-label">
    @Html.LabelFor(model => model.UnitPrice)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.UnitPrice)
    @Html.ValidationMessageFor(model => model.UnitPrice)
</div>

1 个答案:

答案 0 :(得分:2)

你能试试这段代码吗?

@model MvcFirstSample.Models.OrderModel
    @{
        ViewBag.Title = "create";
    }

    <h2>create</h2>

    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)


        //.....

    @Html.Partial("OrderDetail", Model.OrderDetailModels)
}

,部分视图将是

@model List<MvcFirstSample.Models.OrderDetailModel>
@{
    ViewBag.Title = "OrderDetail";
}
@* we need to looping the list of Order details here *@

最后,请为OrderModel类型添加自定义模型绑定器

我将很快添加示例代码