0
votes

The problem is very simple :)

I have two models Parent and Child. Parent model contains collection of children. The point is that I'm able to see children in view, but I'm not able to save changes to them. I spent many hours for tying to solve this problem. Any help will be veeeery appreciate.

parent model

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

Child model :

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

my view :

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

and my controller :

// GET: /Parent/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new 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);
}

I'll be very appreciate for any help :/ As i wrote the point is that I'm able to display related children but not able to edit them.

1
Why did you tag this with asp-classic, I don't see any classic asp here.Ryan Mann

1 Answers

0
votes

There is no Children property on Parent, there is a Child property. But the Binding attribute says Children. Change the attribute to...

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