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.