使用JavaScript动态添加表单控件并在ASP.Net Core中处理表单

问题描述

我正在建立一个页面,我需要在其中添加文档模板。每个文档的节数均未知。用户将能够给模板起一个名字,并添加任意数量的部分。该部分将具有名称内容。我在这里遵循了示例: Create dynamic forms that grow at run time 但是,带有部分的集合始终为空。这是我的模型,控制器和视图中的一些代码

NewDocumentviewmodel.cs

public class NewDocumentviewmodel
    {
        public string Name { get; set; }
        public List<Sectionviewmodel> Sections { get; set; }

        public NewDocumentviewmodel()
        {
            this.Sections = new List<Sectionviewmodel>();
        }
    }

这是Sectionviewmode.cs

public class Sectionviewmodel
    {
        public int Id { get; set; }
        public string SectionName { get; set; }
        public string SectionContent { get; set; }
        public int Position { get; set; }
    }

按照上面的链接中的示例,我创建了一个名为Section.cshtml的View文件,其内容如下:

@model Sectionviewmodel
    <input type="text" asp-for="SectionName" class="sections" />
    <input type="text" asp-for="SectionContent" class="contents" />

然后在我的视图中名为SaveTemplate的表单中有以下内容

 <form asp-controller="Templates" asp-action="SaveTemplate">
            <div class="form-group">
                <label asp-for="Name"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <p>
                <a id="addSection" class="btn btn-success">Add new section</a>
                @Html.EditorFor(f => f.Sections)
            </p>
            <div class="form-group" id="sectionContainer">

            </div>


            <button type="submit" class="btn btn-primary">Add document</button>
        </form>

这是添加新部分的JavaScript:

<script>
    var count = 1;

    $('body').on('click','#addSection',function () {

        var i = $(".sections").length;
        var y = $(".contents").length;

        var structure = $('<div>' +
            'Section name:<br />' +
            '<input type = "text" name="Section[' + i + '].SectionName" class = "form-control sections" /><br />' +
            'Section content:<br />' +
            '<textarea name="Section[' + y + '].SectionContent" id = "editor' + count + '" class= "form-control contents" placeholder = "Description" ></textarea >' +
            '</div > ');
        $('#sectionContainer').append(structure);
        CKEDITOR.replace('editor' + count);
        count++;
    });
</script>

我刚创建的控制器中没有太多代码,以查看是否会从中获取所有数据

 the View when debugging:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SaveTemplate(NewDocumentviewmodel model)
        {
            try
            {
                // Todo: Add insert logic here

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

Section集合始终为空的原因是什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)