0

I am trying to bind a child collections from my viewmodels to the domain model in the controller and I do not know how. (I tried using automapper and did not get very far).

I already have all the information on what I am working on, so to save trees I figured it might be easy to put a link, instead of repeating the same code.

MVC Partial View not rendering from an EditorTemplates

This is what I have in my controller so far. I know my child probably needs to be in a for loop or something.

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(ParentVM viewModel)
    {
        if (ModelState.IsValid)
        {

            var child = new Child()
            {
                Name = viewModel.Name,
                DOB = viewModel.DOB,
                Address = viewModel.Address
            };

            var parent = new Parent()
            {
                FirstName = viewModel.FirstName,
                LastName = viewModel.LastName
            };

            //Parent parent = new Parent();              
            //var employee = AutoMapper.Mapper.Map<Parent, ParentVM>(parent);

            db.Parents.Add(parent);
            db.Childs.Add(child);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(viewModel);
    }

The parent is inserted properly but the children (they are three) only insert one and the value are all null except for the parentID.

Community
  • 1
  • 1
Hockey_Fan
  • 99
  • 10

1 Answers1

0

Your code for var child = new Child(){.. does not make sense. Looking at your previous question, ParentVM should not even contain properties for Name, DOB and Address. They seem to be properties of the ChildVM class, not ParentVM (perhaps they are properties of both but can't tell from your code), and in any case your not rendering any controls for ParentVM.Name, ParentVM.DOB etc so they will always be null when you post back (and therefore null when you save to the database).

Its a bit unclear exactly what you trying to do, but if you have correctly used an EditorTemplate for ChildVM, then you can create a Child class using

if (ModelState.IsValid)
{
  ....
  // assumes your using a view model named ChildVM and property Childs is typeof List<ChildVM>
  foreach(ChildVM item in viewmodel.Childs) 
  {
    // Create a new Child based on ChildVM
    var child = new Child()
    {
      Name = item.Name,
      DOB = item.DOB,
      Address = item.Address
    };
    db.Childs.Add(child);
  }
  ....
  db.SaveChanges();
}
  • I was working on a project and decided to step back and work on a test form and resolve/learn all I need to do for my main project. What I am trying to is have a main form (parent) and on that form I will have a section to add/remove rows (childs). Does that make sense? – Hockey_Fan Dec 01 '14 at 01:22
  • OH the ChildVM is for the EditorTemplate, that is why I have the child properties in my ParentVM – Hockey_Fan Dec 01 '14 at 01:26
  • Ok, once again you were right on the money. It worked. I had to change the foreach from viewmodel.Childs to viewModel.Children. I also removed the childs properties from ParentVM and all is working. Do you use automapper? Thanks you so much. – Hockey_Fan Dec 01 '14 at 01:38
  • By the way, I research a lot before I post and I am surprise that there is not many people doing what I am trying to do. I know it is common, to have parent/childs relationship with add/remove rows – Hockey_Fan Dec 01 '14 at 01:41
  • @Cindy, I think there are a few gaps in your knowledge. Looking at your models, it seems they have the same properties, and therefore should be the same type of object and stored in the same table as a hierarchical structure (`ID`, ParentID` `Name` `DOB` etc) where a value of `NULL` for `ParentID` indicates that's its a top level object. With the structure you have at the moment its impossible to add grandchildren objects. –  Dec 01 '14 at 02:12
  • Next, using `EditorTemplate` as I indicated in your previous question is fine for editing existing records, but its not going to work for dynamically adding new records. Look at the html generated. You will have controls named `Child[0].Name`, Child[1].Name` etc. The indexers are critical to binding the collection on postback. To dynamically add child records you need to use jquery to construct the correct html with an index property. [My answer here](http://stackoverflow.com/questions/24026374/adding-another-pet-to-a-model-form/24027152#24027152) may point you in the right direction. –  Dec 01 '14 at 02:18
  • A few gaps? That is an under statement :-) Seriously, I am not following you though. Did you read my four comments above? I removed the same properties. The only null values were Name, DOB and Address. I think I got it right now. I got the main webforms and I want the ability to enter as many rows of children that I want. For example. A team (main form/parent), players(child /add-remove rows). – Hockey_Fan Dec 01 '14 at 02:24
  • Yes, correct that will be step two to use Jquery to add/remove rows. But first, I just wanted to grasp the concept. I learn differently than most people. too old to change. :-) – Hockey_Fan Dec 01 '14 at 02:27
  • Yes, I understand, but to add child elements to your collection you have to use jquery as I per the link in my last comment –  Dec 01 '14 at 02:28
  • If you do not mind me asking, do you use automapper? Once again I appreciate your time. – Hockey_Fan Dec 01 '14 at 02:35
  • No I don't, but I have heard it good and fairly easy to learn and use. –  Dec 01 '14 at 02:43