在MVC中更新Master-Detail / Parent-Child数据

时间:2018-04-27 18:45:00

标签: asp.net post model-view-controller edit master-detail

拥有包含发票主 - 明细样式视图的视图。主人是发票,详细是发票行。我正在尝试获取详细数据项以保存在编辑帖子上,但是在到达控制器上的帖子编辑时详细数据丢失了。因此主数据保存得很好,但显然没有保存细节。

发票类:

public class Invoice
{
    public Invoice()
    {

    }

    [Required]
    [Key]
    public int InvoiceID { get; set; }

    [Required]
    [StringLength(30)]
    [DisplayName("Invoice Number")]
    public string InvoiceNumber { get; set; }

    [Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    [DataType(DataType.Date)]
    [Column(TypeName = "Date")]

    [DisplayName("Invoice Date")]
    public DateTime InvoiceDate { get; set; }

    public List<InvoiceLine> InvoiceLines { get; set; }

    [ForeignKey("Client")]
    public int OwnerClientIDFK { get; set; }

    [DisplayName("Client")]
    public Client Client { get; set; }
}

发票行类:

public class InvoiceLine
{
    public InvoiceLine()
    {

    }

    [Key]
    [Required]
    public int InvoiceLineId { get; set; }

    [Required]
    [StringLength(255)]
    [DisplayName("Item")]
    public string ItemName { get; set; }

    [DisplayName("Description")]
    public string ItemDescription { get; set; }

    [Required]
    public int Quantity { get; set; }

    [Required]
    [DisplayFormat(DataFormatString = "{0:C}", ApplyFormatInEditMode = true)]
    public decimal Value { get; set; }

    [ForeignKey("ParentInvoice")]
    public int InvoiceID { get; set; }

    public Invoice ParentInvoice { get; set; }

} 

Controller Edit(get):

    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        // Invoice invoice = db.Invoices.Find(id);
        Invoice invoice = db.Invoices.Include(i => i.InvoiceLines)
                            .Include(i => i.Client)
                            .Where(c => c.InvoiceID == id).FirstOrDefault();

        if (invoice == null)
        {
            return HttpNotFound();
        }
        ViewBag.OwnerClientIDFK = new SelectList(db.Clients, "ClientId", "CompanyName", invoice.OwnerClientIDFK);
        return View(invoice);
    } 

Controller Edit(post):

    public ActionResult Edit([Bind(Include = "InvoiceID,InvoiceNumber,InvoiceDate,OwnerClientIDFK")] Invoice invoice)
    {
        if (ModelState.IsValid)
        {
            db.Entry(invoice).State = EntityState.Modified;

            foreach (var invLine in invoice.InvoiceLines)
            {
                db.Entry(invLine).State = EntityState.Modified;
            }

            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.OwnerClientIDFK = new SelectList(db.Clients, "ClientId", "CompanyName", invoice.OwnerClientIDFK);
        return View(invoice);
    } 

所以在上面,当它到达foreach时,它会抛出异常因为InvoiceLines为null。

查看:

@model DemoApp.Entities.Invoice

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Invoice</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.InvoiceID)

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

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

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

    <div class="form-group">
        <h2>Invoice Lines</h2>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="row">
            <div class="col-md-8">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Item</th>
                            <th>Description</th>
                            <th>Qty</th>
                            <th>Unit Value</th>
                        </tr>
                    </thead>
                    <tbody>
                        @for (int i = 0; i < Model.InvoiceLines.Count; i++)
                        {
                            <tr>
                                <td>@Html.EditorFor(x => x.InvoiceLines[i].ItemName, new { htmlAttributes = new { @class = "form-control" } })</td>
                            </tr>
                        }
                    </tbody>

                </table>
            </div>
        </div>

    </div>

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

</div>
}

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

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

如何更新详细信息/子数据?

任何帮助表示赞赏。提前谢谢。

3 个答案:

答案 0 :(得分:1)

您没有在编辑后期操作方法

上绑定InvoiceLines

public ActionResult Edit([Bind(Include =“InvoiceID,InvoiceNumber,InvoiceDate,OwnerClientIDFK,InvoiceLines”)]发票发票)     {

答案 1 :(得分:0)

您可能需要在获得父实体时加载发票行。

db.Entry(invoice).Collection(i =&gt; i.InvoiceLines).Load()应该这样做。

答案 2 :(得分:0)

首先,这是一个棘手的场景。有很多活动部件。我对此非常感兴趣并编写了一个示例应用程序。 :)

这是GitHub上repo的链接: https://github.com/benday/asp-mvc-invoice-sample

有一些事情正在密谋导致代码出现问题。

1)具有讽刺意味的是,您在编辑(发票模型)方法中拥有的Bind []正在妨碍您。如果你完全删除它,ASP MVC将尝试绑定所有内容。现在,它只绑定你告诉它绑定的东西,因为你不包含InvoiceLines集合,那么它就是null。

2)如果您希望ASP MVC尝试将数据绑定到模型中,则需要将该数据POST回服务器。如果这些发票行不是html格式且未表示为表单字段,那么该数据将会丢失。

您必须绘制发票行的代码缺少填充InvoiceLine对象所需的大多数字段。

  

@ Html.EditorFor(x =&gt; x.InvoiceLines [i] .ItemName,new {   htmlAttributes = new {@class =“form-control”}})

Editor Template for the InvoiceLine class

在我的示例代码中,我为InvoiceLine类创建了一个编辑器模板。这允许我通过调用@Html.EditorFor(model => model.Invoice.InvoiceLines) asdf

轻松地为InvoiceLines创建可绑定的html

我知道这不是最简单的答案,但我希望这可以帮助你克服困难。