簡體   English   中英

MVC 將復雜對象傳遞給控制器​​以進行保存

[英]MVC Passing a Complex Object to the controller for saving

我正在用 MVC 和實體框架編寫一個網頁。 我有一個附有訂單項的訂單,想將一個復雜的對象返回給控制器進行處理。

我現在已經包含了所有代碼。

我的觀點

@model BCMManci.ViewModels.OrderCreateGroup

@{
    ViewBag.Title = "Create";
}
<h2>New Order</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <h4>@Html.DisplayFor(model => model.Order.Customer.FullName)</h4>

    <table>
        <tr>
            <td><b>Order Date:</b> @Html.DisplayFor(model => model.Order.OrderDate)</td>
            <td><b>Status:</b> @Html.DisplayFor(model => model.Order.OrderStatus.OrderStatusName)</td>
        </tr>
        <tr>
            <td colspan="2">
                <b>Notes</b>
                @Html.EditorFor(model => model.Order.Notes, new { htmlAttributes = new { @class = "form-control" } })
            </td>
        </tr>
    </table>
        @Html.ValidationMessageFor(model => model.Order.Notes, "", new { @class = "text-danger" })
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })


        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <td>Name</td>
                    <td>Price</td>
                    <td>Discount</td>
                    <td>Total</td>
                    <td>Quantity</td>
                </tr>
            </thead>
            <tbody>
                @foreach (var product in Model.ProductWithPrices)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => product.ProductName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => product.SellingPrice)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => product.DiscountPrice)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => product.TotalPrice)
                        </td>
                        <td>
                            @Html.EditorFor(modelItem => product.Quantity, new { htmlAttributes = new { @class = "form-control" } })
                        </td>
                    </tr>
                }
            </tbody>
        </table>

        <input type="submit" value="Create" class="btn btn-default" />
}
<div class="btn btn-danger">
    @Html.ActionLink("Cancel", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

}

控制器

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Order,ProductWithPrices,Order.Note,product.Quantity")] OrderCreateGroup order)
    {
        try
        {
            if (ModelState.IsValid)
            {
                db.Orders.Add(order.Order);

                foreach (var orderItem in order.ProductWithPrices.Select(item => new OrderItem
                {
                    OrderId = order.Order.OrderId,
                    ProductId = item.ProductId,
                    Quantity = item.Quantity,
                    ItemPrice = item.SellingPrice,
                    ItemDiscount = item.DiscountPrice,
                    ItemTotal = item.TotalPrice
                }))
                {
                    db.OrderItems.Add(orderItem);
                }
                db.SaveChanges();
                return RedirectToAction("ConfirmOrder", new {id = order.Order.OrderId});
            }
        }
        catch (DataException /* dex */)
        {
            //TODO: Log the error (uncomment dex variable name and add a line here to write a log.
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
        ViewBag.Products = db.Products.Where(model => model.IsActive == true);

        PopulateDropdownLists();
        return View(order);
    }

數據來源

public class OrderCreateGroup
{
    public OrderCreateGroup()
    {
        ProductWithPrices = new List<ProductWithPrice>();
    }

    public Order Order { get; set; }
    public ICollection<ProductWithPrice> ProductWithPrices { get; set; }
}

public class ProductWithPrice : Product
{
    public decimal SellingPrice { get; set; }
    public decimal DiscountPrice { get; set; }

    public int Quantity { get; set; }

    public decimal TotalPrice { get; set; }
}

但是,在表單上輸入的值不會被傳遞。 所以我無法在控制器中訪問它們。 'productWithPrices' 集合為空,盡管網頁上有數據。

我嘗試將其設為異步,並嘗試更改如下所示的 ActionLink 按鈕,但它沒有到達控制器。

@Html.ActionLink("Create", "Create", "Orders", new { orderCreateGoup = Model }, null)

這是控制器,但它現在沒有意義,因為在頁面的數據源中傳遞的參數。

public ActionResult Create(OrderCreateGroup orderCreateGoup)

拜托,你能告訴我這樣做的最佳方式嗎?

在您的OrderCreateGroup類中,將集合初始化為空列表。

public class OrderCreateGroup
{
    public OrderCreateGroup()
    {
       ProductWithPrices = new List<ProductWithPrice>();
    }
    public Order Order { get; set; }
    public ICollection<ProductWithPrice> ProductWithPrices { get; set; }
}

您需要添加@Html.HiddenFor(m => m.SellingPrice)以及類似的其他使用 DisplayFor 的綁定字段,如果您想將它們發回控制器。

注意:為了您的利益,當您的頁面在瀏覽器中呈現時,請嘗試查看生成的 HTML 代碼,並查看在帶有 name 屬性的<form>標記內生成了哪些標記。

確保從復雜對象綁定適當的屬性,如下所示:

@model  BCMManci.ViewModels.OrderCreateGroup

...
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">


        ...
        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.OrderCreateGroup.Order.Quantity, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.OrderCreateGroup.Order.Quantity, "", new { @class = "text-danger" })
            </div>
        </div>



        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

注意:model.OrderCreateGroup.Order.Quantity 將是您訂單的屬性之一。 希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM