MVC .Net create model and related models at same t

2019-03-06 08:24发布

问题:

I have a model called Company and company can have 1 or more directors. I want to be able to create any number of directors at the same time as creating a company.

I made the Create view of the of the Director a partial view:

@using (Ajax.BeginForm("Create", 
                       "Director", 
                       new AjaxOptions { 
                         HttpMethod = "POST", 
                         UpdateTargetId = "partial", 
                         InsertionMode = InsertionMode.InsertAfter }))
{
 @Html.EditorFor(model => model.Title)
 ...
}

On the Create view of the Company I have a button which loads the partial Create view of the Director into a container:

$.get('@(Url.Action("Create", "Director"))', function (result) {  
            $('#partial').append(result);
        });

This allows the input controls of the Director to be dynamically loaded into the Create view of the Company.

My question is how to handle the creation of Directors at the same time as the company? Or do I need to only allow creation of Directors on Edit and not Create?

回答1:

I started learning mvc few days ago and today I had to do something similar.

I wanted to save multiple dates at the same time. Here is the simplified code:

View:

<input type="text" name="Date" />

Controller:

public ActionResult Create(List<DateTime> Date)
{
    //Saving goes here
}

This way date from every text field named "Date" will be available in List Date.