如何使用动态创建的只读元素提交 MVC razor beginform

How do I submit MVC razor beginform with dynamically created, readonly elements

我正在尝试构建一个表单,该表单将使用 javascript 动态创建只读输入并将这些值与模型值一起传递到控制器中,但我的控制器方法中的 FormCollection 仅包含模型值,不包含模型值输入值。对我做错的任何帮助都会很棒。这是我的代码:

Model.Courses 包含 int CourseId 和 string CourseName。我正在构建具有 CourseName 值的只读输入以传递到 FormCollection 中以建立每个训练营中包含的课程的顺序。

查看:

    <div class="container">
<div class="row">
    <div class="col-xs-12">
        <h2>Create Bootcamp</h2>

        @using (Html.BeginForm("Create", "LMSBootcamp", FormMethod.Post))
        {
            @Html.AntiForgeryToken()

            <div class="form-horizontal">
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                <div class="form-group">
                    @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="row">
                    <div class="col-xs-6 w-50">
                        <h5>Course Order</h5>
                        <ol id="orderContainer">

                        </ol>
                    </div>
                    <div class="col-xs-6 w-50">
                        <h5>Available Courses</h5>
                        <ul>
                            @foreach (var course in Model.Courses.OrderBy(a=>a.CourseName))
                            {
                                <li id="@course.CourseId" onclick="Add_Course()" data-arg="@course.CourseId">@course.CourseName</li>
                            }
                        </ul>
                    </div>
                </div>
                


                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Create" class="btn btn-default" />
                    </div>
                </div>
            </div>
        }

        <div>
            @Html.ActionLink("Back to List", "Index")
        </div>
    </div>
</div>
<script type="text/javascript">
function Add_Course() {
    var courseName = event.target.innerHTML;
    var courseId = event.target.getAttribute('data-arg');

    //create the readonly input for the course desired
    var order = document.createElement("input");
    order.readOnly = true;
    order.setAttribute("type", "text");
    order.setAttribute("value", courseName);
    order.classList.add("form-control", "text-box", "single-line");

    //create li element
    var listElement = document.createElement("li");
    listElement.onclick = function Remove_Course() {
        var element = event.target
        element.remove();
    }
    //add input to list element
    listElement.appendChild(order);

    //add list element to container
    var orderContainer = document.getElementById("orderContainer");
    orderContainer.appendChild(listElement);
}

控制器:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(FormCollection courseOrder)
    {
        
        return RedirectToAction("Index");
    }

谢谢!

在提交之前,请确保那些动态添加的输入具有正确的型号名称,您应该没问题。所以在你的例子中它会类似于这样:

<input type="text" name="courseName[0]" value="courseName 1"/>
<input type="text" name="courseName[1]" value="courseName 2"/>
<input type="text" name="courseName[3]" value="courseName 3"/>

模型绑定器会自动创建一个字符串列表,其中包含这 3 个字符串(“courseName 1”、“courseName 2”、“courseName 3”),并将其分配给相应的 属性,在这种情况下值。

这是一个演示:

型号:

public class FormModel {
        public string Title { get; set; }
        public List<Course> Courses { get; set; }
    }
    public class Course {
        public int CourseId { get; set; }
        public string CourseName { get; set; }

    }

查看(在表单提交之前为添加的每个输入添加名称):

@model FormModel


        <div class="row">
            <div class="col-xs-12">
                <h2>Create Bootcamp</h2>

                @using (Html.BeginForm("Create", "LMSBootcamp", FormMethod.Post, new { id = "myForm" }))
                {
                    @Html.AntiForgeryToken()

                    <div class="form-horizontal">
                        <hr />
                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                        <div class="form-group">
                            @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-xs-6 w-50">
                                <h5>Course Order</h5>
                                <ol id="orderContainer">
                                </ol>
                            </div>
                            <div class="col-xs-6 w-50">
                                <h5>Available Courses</h5>
                                <ul>
                                    @foreach (var course in Model.Courses.OrderBy(a => a.CourseName))
                                    {
                                        <li id="@course.CourseId" onclick="Add_Course()" data-arg="@course.CourseId">@course.CourseName</li>
                                    }
                                </ul>
                            </div>
                        </div>



                        <div class="form-group">
                            <div class="col-md-offset-2 col-md-10">
                                <input type="submit" value="Create" class="btn btn-default" />
                            </div>
                        </div>
                    </div>
                }

                <div>
                    @Html.ActionLink("Back to List", "Index")
                </div>
            </div>
        </div>
        @section scripts{
            <script type="text/javascript">
                function Add_Course() {
                    var courseName = event.target.innerHTML;
                    var courseId = event.target.getAttribute('data-arg');

                    //create the readonly input for the course desired
                    var order = document.createElement("input");
                    order.readOnly = true;
                    order.setAttribute("type", "text");
                    order.setAttribute("value", courseName);
                    order.classList.add("form-control", "text-box", "single-line");

                    //create li element
                    var listElement = document.createElement("li");
                    listElement.onclick = function Remove_Course() {
                        var element = event.target
                        element.remove();
                    }
                    //add input to list element
                    listElement.appendChild(order);

                    //add list element to container
                    var orderContainer = document.getElementById("orderContainer");
                    orderContainer.appendChild(listElement);
                }
                //add name before form submit
                $('#myForm').submit(function () {
                    var i = 0;
                    $("#orderContainer li").each(function () {
                        $(this).find("input").attr("name", "courseName[" + i+"]");
                        i++;
                    })
                    // DO STUFF...
                    return true; // return false to cancel form action
                });
    </script>
}

控制器:

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(FormCollection courseOrder)
        {

            return Ok();
        }

结果: