动态添加文本框并将其发布到控制器mvc

时间:2019-07-06 06:17:36

标签: jquery asp.net-mvc

我是mvc的新手。对于我的应用程序,我已经在视图中创建了collection。可以说我必须第一次显示姓名和地址。如果用户单击复制,则应克隆名称和地址的div。甚至我使用Jqueryit剂量文本框克隆它。而且我必须将所有数据提交回控制器。但是它只发布第一个条目

I have created viewmodel and loop in view to display those in view. As index is 0 initially it is not displaying those text box. 

    public class Person
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }
    public class PersonVM
    {
        public PersonVM()
        {
            Persons = new List<Person>();
        }
        public IList<Person> Persons { get; set; }
    }




    @model MvcApplication5.Models.PersonVM
@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<script src="~/Script/JavaScript.js"></script>
<div class="example-1">

    @using (Html.BeginForm("Create", "Person", FormMethod.Post, new { @id = "formpost", @class = "main-form" } ))
    {

        <div class="example-2">

            @for (int i = 0; i < Model.Persons.Count(); i++)
            {
                <p>Example one</p>
                <p>Example two</p>

                @Html.TextBoxFor(p => p.Persons[i].Name, null, new { @class = "form-control" })

                @Html.TextBoxFor(p => p.Persons[i].Address, null, new { @class = "form-control" })

            }

            <button type="button" class="btn-copy">Copy</button>

        </div>
        <input type="submit" id="submit" name="Submit" />

    }


</div>

<script>
    $(function () {
        $(".btn-copy").on('click', function () {
            var ele = $(this).closest('.example-2').clone(true);
            console.log(ele.find('input'));
            //var currentIndex = $(ele).split("[")[1][0];
            //var newIndex = Number(currentIndex) + 1;
            ele.find('input').each(function () {
                console.log($(ele));
                this.id = this.id.replace('0', '[' + 2 + ']');
                this.name = this.name.replace('[0]', '[' + 2 + ']');
                //$(ele).attr("name", $(ele).attr("name").replace(currentIndex, newIndex));
            });
            $(this).closest('.example-2').after(ele);
        });
        $(".main-form").on("submit", function () {
            //You might need to replace the selector here with something better and
            //repeat this for the name as well, or modify it to work with the whole div.
            //$.each($(".example-2"), function (index, inputContainer) {
            //    $.each($(inputContainer).children("div").children("input"), function (inputIndex, input) {
            //        var currentIndex = $(input).attr("name").split("[")[1][0];
            //        $(input).attr("name", $(input).attr("name").replace(currentIndex, index));
            //    });
            //});
            console.log($('.example-2').val);
        });
    });
</script>

1 个答案:

答案 0 :(得分:0)

编辑:-我已经仔细地查看了代码,然后重新创建了它。我做了一些小的更改,但是现在看起来是这样。

//My Controller action methods
    public IActionResult Index()
    {
        var emptyModel = new PersonVM() {
            Persons = new List<Person>()
        };
        emptyModel.Persons.Add(new Person());
        return View(emptyModel);
    }

    [HttpPost]
    public IActionResult Index(PersonVM people)
    {
        return View(people);
    }

我没有对视图进行任何更改。但我在这里都包括了

@model PersonVM

<div class="example-1">

    @using (Html.BeginForm("Create", "Person", FormMethod.Post, new { @class = "main-form"}))
    {


        <div class="example-2">


            <div>

                @for (int i = 0; i < Model.Persons.Count(); i++)
                {
                    <p>Example one</p>
                    <p>Example two</p>

                    @Html.TextBoxFor(p => p.Persons[i].Name, null, new { @class = "form-control" })

                    @Html.TextBoxFor(p => p.Persons[i].Address, null, new { @class = "form-control" })

                }

                <button type="button" class="btn-copy">Copy</button>
            </div>
        </div>
        <input type="submit" name="Submit" />


    }


</div>
<script>
    $(function () {
        $(".btn-copy").on('click', function () {
            var ele = $(this).closest('.example-2').clone(true);
            $(this).closest('.example-2').after(ele);
        });
        $(".main-form").on("submit", function () {
            //You might need to replace the selector here with something better and
            //repeat this for the name as well, or modify it to work with the whole div.
            $.each($(".example-2"), function (index, inputContainer) {
                $.each($(inputContainer).children("div").children("input"), function (inputIndex, input) {
                    var currentIndex = $(input).attr("name").split("[")[1][0];
                    $(input).attr("name", $(input).attr("name").replace(currentIndex, index));
                });
            });
        });
    });
</script>

这是我提交的表格。 enter image description here

这是调试输出。 enter image description here

希望这可以解决您的问题。一个陷阱是每次克隆时都必须清除“人员”名称和字段的值,但这很容易实现。

您正在看到此信息,因为所有正在提交的文本框都具有相同的索引,并且发生模型绑定时,每个新值都将覆盖现有值。您有两种解决方法。在您的点击侦听器中分配新索引,或者等到用户提交表单为止。这是代码示例。

示例-1:在添加新文本框之后更新索引。

<script>
    //This assumes sequential indices.
    $(function () {
        $(".btn-copy").on('click', function () {
            var ele = $(this).closest('.example-2').clone(true);
            var currentIndex = $(ele).split("[")[1][0];
            var newIndex = Number(currentIndex) + 1;
            $(ele).attr("name", $(ele).attr("name").replace(currentIndex, newIndex);
            $(this).closest('.example-2').after(ele);
        })
    });
</script> 

示例-2:继续使用当前方法,并在提交时应用索引。

<script>
    $(function () {
        $(".btn-copy").on('click', function () {
            var ele = $(this).closest('.example-2').clone(true);
            $(this).closest('.example-2').after(ele);
        });
        $("{selector for form}").on("submit", function() {
            //You might need to replace the selector here with something better and 
            //repeat this for the name as well, or modify it to work with the whole div.
            $.each("input[name='Persons[i].Address']", function(index, input){
                var currentIndex = $(input).split("[")[1][0];
                var newIndex = Number(currentIndex) + 1;
                $(input).attr("name", $(input).attr("name").replace(currentIndex, newIndex);                
            });
        });
    })


</script>