I want to create a parent object with child/related objects in the same view. An example would be: create one Father (with some name) along with all his sons (with their names). I have created a view model:
public class FatherViewModel {
public Father father {get; set;} // has 1 property Name
public List<Son> {get; set;} // has 1 property Name
}
My question is, how do I get the list of Sons back from the view when the post is performed? I have tried using HiddenFor for each Son id, but no matter what, the list is empty when returned to the controller.
UPDATE:
I tried the Editor Template example by Shyju described below, but my editor is never called. I have 1 object:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int? FatherId { get; set; }
public virtual ICollection<Person> Children { get; set; }
}
I did this:
- Scaffolded a full controller for Person with index, create, edit...
- Created EditorTemplates folder in Views->Person
Created Person.cshtml:
@model TestEditorTemplate.Models.Person <div> <h4>Child</h4> @Html.TextBoxFor(s => s.Name) @Html.HiddenFor(s => s.Id) </div>
Added
@Html.EditorFor(m => m.Children)
to Create.cshtml
Questions:
- How can
@Html.EditorFor(m => m.Children)
possibly work with the editor template whenm.Children
is a collection ofPerson
and not a singlePerson
? - I want to create (not edit) a father including children at the same time. That means that I have no Ids to pass to the Create view to start with. How can this work? From the example by Shyju, the Ids are already created beforehand?? Or did I just misunderstand the example?