我有一个表单,其中有一个部分使用BeginCollectionItem生成的jQuery 选项卡。这是通过一对多关系完成的。我可以在表单中创建多个选项卡并可以提交它(newForm.cshtml)。但是,当涉及到编辑时,尤其是当我必须检索表单时(多个选项卡填充了信息),我有点卡在这里。
所以场景很简单。我有一个显示提交表单列表的表格,并且可以单击一行的编辑链接来编辑检索到的表单。此时,我只能在 NewForm 中检索 Name,但无法检索与 Family 选项卡关联的其他 Names。
模型:
public class NewForm
{
public int NewFormId { get; set; }
public string Name { get; set; }
public ICollection<Family> Families{ get; set; }
}
public class Family
{
public int FamilyId { get; set; }
public string Name { get; set; }
public int NewFormId { get; set; }
public virtual NewForm NewForm{ get; set; }
}
编辑.cshtml:
@model Test.Models.NewForm
@using (Html.BeginForm("Edit", "NewForm", FormMethod.Post))
{
<p>Your Name</p>
@Html.EditorFor(m => m.Name)
<button type="button" id="addFamily" name="addFamily">Add Family</button>
<div id="tabs">
<ul>
<li><a href="#tabs-family">Family 1</a></li>
</ul>
<div id="tabs-family">
@Html.Action("AddNewFamily", "NewForm")
</div>
</div>
<button type="submit">Save</button>
}
<script>
$(function () {
var tabTemplate = "<li><a href='#{href}'>#{label}</a></li>",
familyTabCounter = 2,
var tabs = $("#tabs").tabs();
$('#addFamily').on('click', function (event) {
$.ajax({
url: '/NewForm/AddNewFamily',
}).success(function (partialView) {
addTab(partialView, this.url);
});
event.preventDefault();
});
// Actual addTab function: adds new tab using the input from the form above
function addTab(partialView, url) {
if (url == "/NewForm/AddNewFamily") {
var label = "Family " + familyTabCounter,
id = "tabs-family" + familyTabCounter,
li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label));
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'><p>" + partialView + "</p></div>");
tabs.tabs("refresh");
familyTabCounter++;
}
}
});
</script>
家庭.cshtml:
@model Test.Models.Family
<div class="editorRow">
@using (Html.BeginCollectionItem("families"))
{
@Html.EditorFor(m => m.Name)
}
</div>
控制器:
public PartialViewResult AddNewFamily()
{
return PartialView("~/Views/NewForm/PartialView/Family.cshtml");
}
public ActionResult Edit(int? id)
{
NewForm form = db.NewForms
.Include(i => i.Families)
.Where(x => x.NewFormId == id)
.Single();
return View(form);
}
如何检索与 newForm 关联的家庭(选项卡)的信息?
编辑
@using (Html.BeginForm("Edit", "NewForm", FormMethod.Post))
{
<p>Your Name</p>
@Html.EditorFor(m => m.Name)
<button type="button" id="addFamily" name="addFamily">Add Family</button>
@{int number = 1;}
@foreach (var family in Model.Families)
{
<div id="tabs">
<ul>
<li><a href="#tabs-family">Family @number</a></li>
</ul>
<div id="tabs-family">
@Html.Partial("../NewForm/Family", family)
</div>
</div>
number++;
}
<button type="submit">Save</button>
}
我已经反映了斯蒂芬的建议并且检索多个家庭正在工作,但现在我面临另一个问题,我无法为每个家庭创建每个选项卡。我尝试使用我的代码,但它创建了选项卡,但它被放置在一个奇怪的地方。有什么建议么?