微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用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 举报,一经查实,本站将立刻删除。