在单个视图中编辑多个相关表

时间:2016-07-24 10:44:47

标签: c# asp.net-mvc entity-framework asp.net-mvc-4

我有四个表,有三个一对多的关系,我想在一个视图中编辑所有这四个表。这是这些表的模型结构:

模型1(基表):

    public partial class benedet
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public benedet()
        {
            this.bankdets = new HashSet<bankdet>();
            this.damagedets = new HashSet<damagedet>();
            this.imagedets = new HashSet<imagedet>();
        }

        public int id { get; set; }
        [Key]
        public string beneid { get; set; }
        public string name { get; set; }

        //More Properties....

        public virtual ICollection<bankdet> bankdets { get; set; }

        public virtual ICollection<damagedet> damagedets { get; set; }

        public virtual ICollection<imagedet> imagedets { get; set; }
    }

模型2(子表):

    public partial class bankdet
    {
        public int id { get; set; }
        public string beneid { get; set; }

        //More Properties....

        public virtual benedet benedet { get; set; }
    }

模型3(子表):

    public partial class damagedet
    {
        public int id { get; set; }
        public string beneid { get; set; }
        public string name { get; set; }

        //More Properties.....

        public virtual benedet benedet { get; set; }
    }

模型4(子表):

public partial class imagedet
{
    public int id { get; set; }

    public string beneid { get; set; }
    public string url { get; set; }
    public string desc { get; set; }

    public virtual benedet benedet { get; set; }
}

模型1使用密钥beneid与模型2,3和4具有一对多关系。我试图在单个视图中编辑这些模型的数据,但只修改了基本模型(表1),而子模型则没有。 我还尝试使用[ForeignKey("beneid")]属性显式设置密钥,但未成功。 以下是我的编辑方法和视图供参考。

        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            benedet benedet = db.benedets.Find(id);
            if (benedet == null)
            {
                return HttpNotFound();
            }
            benedet.imagedets = (from o in db.imagedets where o.beneid == benedet.beneid select o).ToList();
            benedet.bankdets = (from p in db.bankdets where p.beneid == benedet.beneid select p).ToList();
            benedet.damagedets = (from i in db.damagedets where i.beneid == benedet.beneid select i).ToList();
            return View(benedet);
        }

        // POST: BeneficiaryMaster/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(benedet benedet)
        {

            if (ModelState.IsValid)
            {

                db.Entry(benedet).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(benedet);
        }

查看:

@model IdentitySample.Models.benedet
@using System.Text;
@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

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

    <div class="form-horizontal">
        <h4>benedet</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.beneid)
        <input type="hidden" id="id" name="id" value="@Model.id" />
        <table class="table table-striped table-bordered table-condensed">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.name)
                </th>
                <!-- More headers..... -->              


            </tr>
            <tr>
                <td>
                    @Html.EditorFor(modelItem => Model.name, new { htmlAttributes = new { @class = "form-control" } })
                </td>
               <!-- More Data.... -->                   
            </tr>
        </table>
        <h3>Bank Details</h3>
        <table class="table table-striped table-bordered table-condensed">
            <tr>
              <!--Headers-->
            </tr>
            @foreach (var item in Model.bankdets)
            {
                var i = 0;

                <tr>
                   <!--Data-->
                </tr>
                i++;
            }
        </table>




        <h3>Damage Records</h3>
        <table class="table table-striped table-bordered table-condensed">
            <tr>
                <th>
                    Name
                </th>
               <!--Headers -- >
            </tr>
            @foreach (var item in Model.damagedets)
            {
                var i = 0;
                <tr>
                    <td>
                        @Html.EditorFor(model => item.name, new { htmlAttributes = new { @id = "damagedets[@i].name", @name = "damagedets[@i].name", @class = "form-control" } })
                    </td>
                 <!-- Data -- >
               </tr>
                i++;

            }
        </table>
        <h3>Attachments</h3>
        <table class="table table-striped table-bordered table-condensed">
            <tr>
                @foreach (var item in Model.imagedets)
                {
                    var i = 0;
                    @Html.HiddenFor(modelItem => item.benedet)
                    <input type="hidden" id="imagedets[@i].beneid" name="imagedets[@i].beneid" value="@item.beneid" />
                    <input type="hidden" id="imagedets[@i].url" name="imagedets[@i].url" value="@item.url" />
                    <input type="hidden" id="imagedets[@i].id" name="imagedets[@i].id" value="@item.id" />
                    <th>
                        <input class = "form-control" id="imagedets[@i].desc" name="imagedets[@i].desc" value="@item.desc" />
                        @*@Html.EditorFor(modelItem => item.desc, new { htmlAttributes = new { @id = "imagedets["+i+"].desc", name = "imagedets[@i].desc", @class = "form-control" } })*@
                    </th>
                    <td>

                        <img id="base64image[@i]" src="data:image/jpeg;base64, @ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(item.url))" />
                    </td>
                    i++;


                }
            </tr>
        </table>

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

请指导我如何实现上述目标。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

Link to Answer.

这就是我所做的。

  1. 在我的基本模型中更改了以下内容

    public benedet()
    {
        this.bankdets = new HashSet<bankdet>();
        this.damagedets = new HashSet<damagedet>();
        this.imagedets = new HashSet<imagedet>();
    }
    
    public virtual ICollection<bankdet> bankdets { get; set; }
    
    public virtual ICollection<damagedet> damagedets { get; set; }
    
    public virtual ICollection<imagedet> imagedets { get; set; }
    
  2.     public benedet()
        {
            this.bankdets = new List<bankdet>();
            this.damagedets = new List<damagedet>();
            this.imagedets = new List<imagedet>();
        }
        public virtual List<bankdet> bankdets { get; set; }
    
        public virtual List<damagedet> damagedets { get; set; }
    
        public virtual List<imagedet> imagedets { get; set; }
    
    1. 将视图中的所有foreach循环更改为for循环。

    2. 编辑HTTPPOST EDIT方法以迭代所有项目     这样:

          [HttpPost]
          [ValidateAntiForgeryToken]
          public ActionResult Edit(benedet benedet)
          {
      
              if (ModelState.IsValid)
              {
                 for(int i=0;i<benedet.damagedets.Count;i++)
                  {
                      db.Entry(benedet.damagedets[i]).State = EntityState.Modified;
                  }
                  for (int i = 0; i < benedet.bankdets.Count; i++)
                  {
                      db.Entry(benedet.bankdets[i]).State = EntityState.Modified;
                  }
                  for (int i = 0; i < benedet.imagedets.Count; i++)
                  {
                      db.Entry(benedet.imagedets[i]).State = EntityState.Modified;
                  }
                  db.Entry(benedet).State = EntityState.Modified;
                  db.SaveChanges();
                  return RedirectToAction("Index");
              }
              return View(benedet);
          }