1

I have a form that has a section where it uses jQuery tab generated by BeginCollectionItem. This is done by one-to-many relationship. This is a continuation from this post. I can create multiple tabs within the form and can submit it. Now, I want to post the edited fields. I am a newbie for this, and I think I need to call my child entity to add or delete but not so sure about this. I'd appreciate it if you can give me a sample code for this.

So when I click on edit button, in my debugger the NewForm entity loads all edited fields including associated Family fields, but the FamilyId is always null when it is initially loaded.

Model:

public class NewForm
{
    public int NewFormId { get; set; }
    public string Name { get; set; }

    public ICollection<Family> Families{ get; set; }
}

public class Family
{
    public int FamilyId { get; set; }
    public string Name { get; set; }   

    public int NewFormId { get; set; }
    public virtual NewForm NewForm{ get; set; }
}

I ran my for loop because the loaded newForm's family entities' newFormIds were nulls.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(NewForm newForm)
    {            
       if (ModelState.IsValid)
       {
           db.Entry(newForm).State = EntityState.Modified;
           db.SaveChanges();
           return RedirectToAction("Index");
       }

        return View(newForm);
    }

but it throws an error:

Attaching an entity of type 'Test.Models.Family' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

What do I need to do in the controller in order for me to post edit successfully when I changed the fields or added/deleted tabs in family section?

Community
  • 1
  • 1
bbusdriver
  • 1,577
  • 3
  • 26
  • 58
  • I'm just wondering (not being a smart-a**), but why are you worried about the `Family` object when you are editing the `NewForm` object? When you edit a `Family` record, you can then correspond that to a `NewForm` object (1 `NewForm` can have many `Family`) – Grizzly Nov 21 '16 at 20:54
  • 1
    On view you can add `@Html.HiddenFor(m => FamilyId )` and send with `NewForm `to controller – Perdido Nov 21 '16 at 21:26
  • Thanks Perdido. Nulls gone – bbusdriver Nov 21 '16 at 22:38

0 Answers0