我的MVC应用程序有一个经典的父子关系(主细节)。
我想要创建一个单独的页面,在同一页上创建新的父级和子级。我已经添加了一个动作,返回一个局部视图,并将子HTML添加到父视图中,但我不知道如何将动作中新创建的子项与原始父项相关联(换句话说,如何将新的子实体添加到父实体的这些实体集合中)。
我猜测,当我提交表单时,操作应该获取具有其集合中新创建的子项的父实体。
简而言之,应该是创建子实体的动作代码是什么,子实体如何添加到其父实体集合中?
我在这里阅读了很多帖子(和其他网站),但没有找到示例。
应用程序使用MVC 4和Entity Framework 5。
代码示例(我删除了一些代码以使其简单化)。模型是Form(父项)和FormField(子项)实体。
public partial class Form
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<FormField> FormFields { get; set; }
}
public partial class FormField
{
public int ID { get; set; }
public string Name { get; set; }
public int FormID { get; set; }
}
以下部分视图 (_CreateFormField.cshtml) 创建新的表单字段(子级)。@model FormField
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>FormField</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 class="editor-label">
@Html.LabelFor(model => model.FormID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FormID)
@Html.ValidationMessageFor(model => model.FormID)
</div>
</fieldset>
}
以下视图(Create.cshtml)是创建表单的视图。
@model Form
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Form</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>
@Html.ActionLink(
"Add Field",
"CreateFormField",
new { id = -1},
new { @class = "form-field" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<div id="CreateFormField"></div>
@section Scripts {
<script>
$(function () {
$('.form-field').on('click', function (e) {
$.get($(this).prop('href'), function (response) {
$('#CreateFormField').append(response)
});
e.preventDefault();
});
});
</script>
@Scripts.Render("~/bundles/jqueryval")
}
以下操作处理FormController中的创建。[HttpPost]
public ActionResult Create(Form form)
{
if (ModelState.IsValid)
{
db.Forms.Add(form);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
public ActionResult CreateFormField(string id = null)
{
// I guess something is missing here.
return PartialView("_CreateFormField", new FormField());
}
提前致谢,
沙龙。