mvc5 icollection始终为null

时间:2016-03-25 20:04:34

标签: c# asp.net asp.net-mvc-5

问题很简单:)

我有两个模型Parent和Child。父模型包含子集合。关键是我能够看到孩子们,但我无法保存对他们的更改。我花了很多时间来解决这个问题。任何帮助都将受到感谢。

父模型

 namespace WebApplication1.Models
{
    public class Parent
    {
        //public Parent()
        //{
        //    Child = new Collection<Child>();
        //}

        public int ParentId { get; set; }
        public string ZmiennaParent1 { get; set; }

        public ICollection<Child> Child { get; set; }
    }
}

儿童模特:

    namespace WebApplication1.Models
{
    public class Child
    {
        public int ChildId { get; set; }
        public string ZmiennaChild1 { get; set; }

        public int ParentId { get; set; }
        public virtual Parent Parent { get; set; }
    }
}

我的观点:

@for (int i = 0; i < Model.Child.Count(); i++)
{
    @Html.EditorFor(model => Model.Child.ElementAt(i).ZmiennaChild1, new { htmlAttributes = new { @class = "form-control" } })
}

和我的控制员:

// GET:/ Parent / Edit / 5     public ActionResult Edit(int?id)     {         if(id == null)         {             返回新的HttpStatusCodeResult(HttpStatusCode.BadRequest);         }

    var parent = db.Parents.Include(u => u.Child).SingleOrDefault(u => u.ParentId == id);

    if (parent == null)
    {
        return HttpNotFound();
    }
    return View(parent);
}

// POST: /Parent/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(Parent parent)
public ActionResult Edit([Bind(Include="ParentId,ZmiennaParent1, Children")] Parent parent)
{
    if (ModelState.IsValid)
    {
        if (parent.Child != null)
        {
            foreach (Child element in parent.Child)
            {
                db.Entry(element).State = EntityState.Modified;
            }
            db.SaveChanges();
        }

        db.Entry(parent).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(parent);
}

我会非常感谢任何帮助:/正如我写的那样,我能够显示相关的孩子但不能编辑它们。

1 个答案:

答案 0 :(得分:0)

Parent上没有 Children 属性,有一个Child属性。但Binding属性表示儿童。将属性更改为...

public ActionResult Edit([Bind(Include="ParentId,ZmiennaParent1, Child")] Parent parent)