I am trying to create a form which allows the creation and editing of a hierarchy of entities using MVC.
The top level is project which can have 1 or many environments associated with it. The environments are predefined, eg Dev, Test and Prod.
For each environment that is added it is possible to add several interfaces.
So a user would enter the project information. Select which environments which are relevant and then for each environment section add several interfaces.
I've created 3 view models, project, environment and interface. Like so
public class ProjectViewModel
{
public int Id { get; set; }
public string ProjectTitle { get; set; }
public List<SelectListItem> EnvironmentChoices { get; set; }
public List<EnvironmentViewModel> EnvironmentModel { get; set; }
}
public class EnvironmentViewModel
{
public IList<InterfaceViewModel> Interfaces { get; set; }
public string Environment { get; set; }
}
public class InterfaceViewModel
{
public string InterfaceName { get; set; }
}
Then created 1 project template and 2 editor templates for the environment model and the interface model.Like so
<p>
@Html.LabelFor(x => x.ProjectTitle)
@Html.TextBoxFor(x => x.ProjectTitle)
@Html.ValidationMessageFor(x => x.ProjectTitle)
</p>
<p>
@Html.LabelFor(x => x.EnvironmentModel)
@for (int i = 0; i < Model.EnvironmentChoices.Count; i++)
{
@Html.CheckBoxFor(m => m.EnvironmentChoices[i].Selected, new { id = Model.EnvironmentChoices[i].Value })
@Html.HiddenFor(m => m.EnvironmentChoices[i].Value)
@Html.DisplayFor(m => m.EnvironmentChoices[i].Text)
}
</p>
<p>
@Html.EditorFor(x => x.EnvironmentModel)
</p>
for the environment template
@model EnvironmentViewModel
<fieldset style="margin-left: -10px;">
<legend>@Model.Environment</legend>
@Html.ActionLink("Add Interface", "AddInterface", Model, new { @class = "button icon-file-plus" })
@Html.EditorFor(x => x.Interfaces)
</fieldset>
for the interface template
@model InterfaceViewModel
<p>
@Html.LabelFor(x => x.InterfaceName)
@Html.TextBoxFor(x => x.InterfaceName)
@Html.ValidationMessageFor(x => x.InterfaceName)
</p>
What I am finding is that when I click the add button on the environment section. The controller only picks up the environment model and loses the project model context so cannot modify it to add the new interface model.
Am I going about this in the wrong way? If so, are there examples of best practice. If not, what am I doing wrong.
Thanks