【问题标题】:MVC BeginCollectionItemMVC BeginCollectionItem
【发布时间】:2018-02-06 16:40:13
【问题描述】:

我在将部分视图 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);
}

【问题讨论】:

  • 欢迎来到 SO。您能否将标题改写为更自然的内容(用一句话概括您的问题)。标题是人们看到的第一件事,可能会更好地吸引可能提供答案的合适人的注意力。另请注意,没有“MVC 6”。只是旧的 ASP.NET MVC 5 和新的 ASP.NET Core MVC(1.x 和 2.x)

标签: asp.net-mvc razor begincollectionitem


【解决方案1】:

您对Html.BeginCollectionItem("Section") 的使用将Section[xxxx] 附加到名称属性(其中xxxx 是Guid),以便您生成输入

<input name="Section[xxxx].SectionId" .... />

回发到包含名为 Sections 的集合属性的模型。

由于您已经有一个具有该属性的模型,您可以将 POST 方法更改为

[HttpPost]
public ActionResult SOPTopTemplateBuilder(SOPTopTemplateBuilderViewModel soptop)

其他选项包括

  1. 使用现有的 POST 方法并省略“Section”前缀 使用Html.BeginCollectionItem("") 将生成 name="[xxxx].SectionId"
  2. 将 POST 方法签名更改为 public ActionResult SOPTopTemplateBuilder(IEnumerable<Section> section)(其中 参数名称与前缀名称匹配)
  3. 使用BindAttribute 从表单值中“去除”前缀 public ActionResult SOPTopTemplateBuilder([Bind(Prefix = "Section")]IEnumerable&lt;Section&gt; soptop)

作为旁注,您正在编辑数据,因此您应该始终使用视图模型(例如public class SectionViewModel)而不是在视图中使用数据模型。 - What is ViewModel in MVC?

【讨论】:

  • 谢谢!我已经使用了绑定前缀方法并且它有效!我确实必须将其更改为 Section 而不是 Sections,但它现在将所有信息都放入数据库中。
猜你喜欢
  • 1970-01-01
  • 2017-02-15
  • 1970-01-01
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多