-4

I have problem with adding/editing/deleting children list in parent object. In first method Edit(int id) I set current parent but while I'am adding new element of children list the _currentParent object is null. Do you have other idea to resolve this problem ?

public class Parent 
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<Children> Childrens { get; set; }
    public Parent()
    { 
       Childrens = new List<Children>();
    }

}

public class Children
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ParentID { get; set; }
    public Parent Parent { get; set; }
}

public class ParentController : Controller
{   
        private Parent _currentParent 
...
        public ViewResult Edit(int id)
        {
            var parent = _ParentsRepository.Find(id);
            _currentParent = parent;
        }

        public ViewResult AddChildren(string name)
        {
            _currentParent.Childrens.Add(new Children(){Name = name});
        }
...
}
Szymson
  • 990
  • 1
  • 13
  • 28
  • But currently parent object has the list of childrens. – Szymson Feb 11 '18 at 19:45
  • It is not a good design for children to know about parent and parent know about children. It should probably be one or the other, not both. – FCin Feb 11 '18 at 19:51
  • The web is stateless. Every request create a new instance of the controller which initializes `_currentParent` as `null` –  Feb 11 '18 at 21:00
  • so what is the solution ? – Szymson Feb 11 '18 at 21:25
  • Pass the value of the `parentId` to your `AddChildren()` method then create and save the `Children` object to your db. –  Feb 11 '18 at 21:32
  • I want first add children elements and on "Save" button save all. – Szymson Feb 11 '18 at 21:35
  • @Szymson. Then add all the child elements in your `Edit` view (refer [this answer](http://stackoverflow.com/questions/40539321/partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) for one option for doing that) –  Feb 11 '18 at 21:44
  • I don't have BeginCollectionItem method on Html – Szymson Feb 11 '18 at 21:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/164936/discussion-between-stephen-muecke-and-szymson). –  Feb 11 '18 at 22:02

1 Answers1

0

I would do a null check in the Edit method to verify that parent variable is not null. If it is null, then it means that there is no object that has the given id.

Skatedude
  • 343
  • 3
  • 4
  • 12