Search code examples
htmlasp.net-mvcmappingviewmodelchildren

ASP MVC How to create editor for model which have children elements?


I'm new in asp. I must write an application in mvc which have a database where I have a two tables. One table Parent is realted one to many with table Children.

Parent
-------------
parent_id
name


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

When user want to create an element for Parent table, the editor must have an opportunity to add(create) Children.

When user edit Parent then he should have opportunity to delete/edit Children.

There isn't possible to add/edit/delete Children in separete editor

I think I sholuld use a javascript to generate further controls for Child. I can do this but I don't know how to map this html controls to model?

I have wrote this view:

<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>
}

This works fine. But I relly don't know how to map this element on my Parent Model.

Now my Model for create view looks like this:

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 fill this Children by the values from 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 a form.CreatedChildren but it is Null...


Solution

  • You may checkout the following blog post. And the followup about validation.