ASP MVC How to create an editor for a model that has children?

I am new to asp. I have to write an application in mvc that has a database where I have two tables. One Parent table is used for many with the Kids table.

Parent ------------- parent_id name Children ------------- children_id parent_id (foreign key) name 

When the user wants to create an element for the parent table, the editor should be able to add (create) children.

When a user edits Parent, he should be able to delete / edit Children.

Unable to add / edit / delete children in separtet editor

I think sholuld used javascript to create additional controls for Child. I can do this, but I don’t know how to map these html controls for simulation?

I wrote this opinion:

 <script language="javascript" type="text/javascript"> function add_child() { $('#children').append($('<input name="child[' + ++$('#children>input').get().length + ']" />')); } </script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Create Parent</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div>Children:</div> <div id="children"> @Html.TextBox("child[1]") </div> <div> <input onclick="add_child()" type="button" /> </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } 

It works great. But I do not know how to display this element on my parent model.

Now my model for creating is as follows:

 public class ParentModel { public ParentModel() { Children = //... get all children from database } public string Name { get; set; } // this should be an ids of selected children public string[] SelectedChildren { get; set; } // children to display public ICollection<ChildModel> Children { get; set; } } public class ChildModel { public string Name { get; set; } } 

How to populate these children with values ​​from the view?

Controller:

 public class ParentController : Controller { // show form [AcceptVerbs(HttpVerbs.Get)] public ActionResult Index() { ParentModel model = new ParentModel(); return View(model); } // Get Parent and Children [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(ParentModel form) { // I want to read a form.CreatedChildren // but it is Null return View(); } } 

I want to read form.CreatedChildren, but it's Null ...

+4
source share
2 answers

You can check out the following blog post . And follow up on the check.

+5
source

If I understand your model correctly, you need to

 // children to display public ICollection<ChildModel> Children { get; set; } 

in the parent model. In the constructor of ParentModel

 Children = new HashSet<ChildModel>(); 

As for populating the model with data that belongs to your controller. Sort of:

 var parents = from p in context.ParentModels select p; Return View(parents); 
0
source

Source: https://habr.com/ru/post/1345264/


All Articles