部分视图 - ASP.NET MVC 4中的模型绑定

时间:2014-11-21 13:20:01

标签: asp.net-mvc

我的MVC 3应用程序中有2个模型,CustomerOrderOrderDetail。 我的模型OrderDetai l与List

模型

public class CustomerOrder
{
    public int CustomerId { get; set; }
    public int NetPrice { get; set; }
    public List<OrderDetail> Orderlist { get; set; }
    public CustomerOrder()
    {
        Orderlist = new List<OrderDetail>();
    }       
}

public class OrderDetail
{
    public string ProductName { get; set; }
    public int Quantity { get; set; }
    public int Price { get; set; }
    public int TotalPrice {get{ return Price*Quantity;} }       
}

这是我的控制器

public ActionResult CustomerOrder()
{
    return View();
}

[HttpPost]
public ActionResult CustomerOrder(CustomerOrder SelectedOrder)
{
    DataBase dataBase = new DataBase();
    var result = dataBase.InsertData(SelectedOrder);
    ViewData["result"] = result;
    return View();
}

这是CustomerOrder

的我的观点
@model MvcCustomerOrderClass4g.Models.CustomerOrder
@{
    ViewBag.Title = "CustomerOrder";
}

<h2>CustomerOrder</h2>

@using (Html.BeginForm()) {
    <fieldset>
        <legend>CustomerOrder</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.CustomerId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CustomerId)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.NetPrice)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NetPrice)
        </div>    
        <p>
            <input type="submit" value="Submit" />
        </p>
    </fieldset>
}
@{
    if (ViewData["result"] != "" && ViewData["result"] != null)
    {       
    <script type="text/javascript" lang="javascript">
        alert("Data saved Successfully");
    </script>
    }   
}

我的模型OrderDetailList一致。如何在我的视图中将其用作列表? 在这里,我想添加OrderDetail模型。我还为OrderDetails创建了另一个视图,用于在CustomerOrder中将其添加为部分视图。

1 个答案:

答案 0 :(得分:0)

最简单的方法是创建EditorTemplate

@model OrderDetail

    @Html.HiddenFor(m => m.Id)//your model doesn't seem to have an id?
    @Html.DisplayFor(m => m.ProductName)
    @Html.EditorFor(m => m.ProductName)

然后在您使用CustomerOrder模型的视图中执行此操作:

@Html.LabelFor(model => model.OrderList)
@Html.EditorFor(model => model.OrderList)