我在将部分视图 BeginCollectionItem 保存到数据库时遇到了一些问题。我有一个表单,它具有可以添加到页面的动态数量的“部分”,并且在每个字段中都有一个文本框,用户可以在其中输入部分名称。
据我所知,局部视图中的 BeginCollectionItem 工作正常,但是我无法将信息发布到数据库中。在我的其他表单中,我使用 [bind()] 将数据发送到数据库,是否可以将其放入列表中,然后通过绑定发布?
我在下面包含了我的代码: 模型:
namespace project.Models.SetupViewModels
{
public class SOPTopTemplateBuilderViewModel
{
public List<Section> Section { get; set; }
}
public class Section {
public int SectionId { get; set; }
public string SectionText { get; set; }
public string TopTempId { get; set; }
}
}
cshtml:
@model IEnumerable<project.Models.SetupViewModels.Section>
@using (Html.BeginForm("SOPTopTemplateBuilder", "Setup", FormMethod.Post))
{
<div class="main-holder" id="theform">
@foreach(var item in Model)
{
@Html.Partial("_SectionCreator", item)
}
</div>
<button id="add" type="button">Add</button>
<div class="form-group submit-row">
<div class="col-12 float-to-right">
<input type="submit" class="btn btn-default" value="continue" />
</div>
</div>
}
@section Scripts {
<script>
$(document).ready(function () {
var url = '@Url.Action("AddSection")';
var form = $('form');
var recipients = $('#theform');
$('#add').click(function() {
$.post(url, function(response) {
recipients.append(response);
// Reparse the validator for client side validation
form.data('validator', null);
$.validator.unobtrusive.parse(form);
});
});
});
</script>
}
局部视图:
@model project.Models.SetupViewModels.Section
@using HtmlHelpers.BeginCollectionItemCore
@using (Html.BeginCollectionItem("Section"))
{
<div class="new-section">
<div>
<p>New Section</p>
@Html.HiddenFor(m => m.SectionId, new { @class="id" })
@Html.EditorFor(m => m.SectionText, new { @class = "form-control limit-form"})
</div>
</div>
}
控制器:
[HttpPost]
public PartialViewResult AddSection()
{
return PartialView("_SectionCreator", new Section());
}
[HttpGet]
public ActionResult SOPTopTemplateBuilder(){
List<Section> model = new List<Section>();
return View(model);
}
[HttpPost]
public ActionResult SOPTopTemplateBuilder(IEnumerable<Section> soptop)
{
if (ModelState.IsValid)
{}
return View(soptop);
}