简体   繁体   English

使用Javascript动态地将行添加到html表

[英]Dynamically adding rows to an html table, using Javascript

As a beginner MVC programmer I am constantly searching the web for help. 作为一名初学MVC程序员,我不断在网上寻求帮助。 I am trying to dynamically add a row to a HTML table using javascript. 我试图使用JavaScript动态地向HTML表添加一行。 The below code works great, it adds the rows. 下面的代码工作得很好,它添加了行。 The problem is when I return to the controller, the new rows are not there. 问题是当我返回控制器时,新行不在那里。 If I start with 3 rows of data and add 1 or 2 rows, when I click the submit button it returns with only the original 3 records. 如果我从3行数据开始并添加1或2行,当我单击提交按钮时,它仅返回原始3条记录。 Not sure why the below is not returning the new rows I added. 不知道为什么下面没有返回我添加的新行。 Below is a reduced portion of the code. 下面是代码的缩小部分。

Any help will be greatly appreciated. 任何帮助将不胜感激。

Here is my View. 这是我的观点。

@model List<ACES.Models.ENTITY_CONTACTS>

@using (Html.BeginForm("Edit", "Contacts", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div class="form-horizontal">
        <table id="dataTable" class="list-Contacts table-condensed table-striped  table-responsive test">
            <tr>
                <th class="danger text-center">
                    <label>Last Name</label>
                </th>
                <th class="text-center">
                    <label>First Name</label>
                </th>
                <th class="text-center">
                    <label>Title</label>
                </th>
                <th class="text-center">
                    <label>EMail Address</label>
                </th>

            </tr>

            @if (Model != null && Model.Count > 0)
            {
                int j = 0;
                foreach (var i in Model)
                {
                    if (j == 1)
                    {
                        <tr class="contacts-record-template" style="display:none">

                            <td>
                                @Html.TextBoxFor(a => a[j].LASTNAME)
                            </td>
                            <td>
                                @Html.TextBoxFor(a => a[j].FIRSTNAME)
                            </td>
                            <td>
                                @Html.TextBoxFor(a => a[j].TITLE)
                            </td>
                            <td>
                                @Html.TextBoxFor(a => a[j].EMAIL, new { @style = "width: 200px;" })
                            </td>

                        </tr>
                    }

                    <tr class="contacts-record">
                        <td>
                            @Html.TextBoxFor(a => a[j].LASTNAME)
                        </td>
                        <td>
                            @Html.TextBoxFor(a => a[j].FIRSTNAME)
                        </td>
                        <td>
                            @Html.TextBoxFor(a => a[j].TITLE)
                        </td>
                        <td>
                            @Html.TextBoxFor(a => a[j].EMAIL, new { @style = "width: 200px;" })
                        </td>

                    </tr>
                    j++;
                }
            }
        </table>


        @*Display buttons*@
        <input type="button" class="add-button" name="add" value="Add" />

        <div style="text-align:right"><a href="#" id="addNew">Add Contact</a></div>
        <input type="submit" name="submitAction" value="Submit" class="btn btn-primary" onclick="return confirm('Please double check all information before submitting.   Submit Notification?')" />
    </div>


}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.maskedinput.min.js"></script>
<script type="text/javascript">
    $('.phone2').mask('999-999-9999');
    $('.phone').mask('?999-999-9999');


    $(document).ready(function () {
        var count = 0;
        $('.add-button').click(function () {
            count++;
            var template = $('.contacts-record-template').clone()
            template.find('input[type=text]').val(null);
            template.find('input[type=checkbox]').prop('checked', false);
            $.each(template.find('input[type=text]'), function () {
                var name = $(this).attr('name');
                name = name.replace('0', count - 1);
                $(this).attr('name', name);
            });

            $('.list-Contacts').append(template);
            template.removeClass('contacts-record-template').addClass('contacts-record').show();
        })
    });

</script>

Controller. 控制器。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(string submitAction, List<ENTITY_CONTACTS> entity_Contacts)
    {
        if (ModelState.IsValid)
        {
            foreach (var i in entity_Contacts)
            {
                ViewBag.temp = i.LASTNAME;
            }
            db.SaveChanges();
        }
        return View(entity_Contacts);

The problem is, your template input field has name like [1].LASTNAME . 问题是,您的模板输入字段的名称类似于[1].LASTNAME But in your code you are doing a replace on 0 , instead of 1 . 但是在你的代码中,你在0上进行替换,而不是1

Change your code to replace 1 instead of 0 when you try to generate the name value for the dynamically generated input fields. 当您尝试为动态生成的输入字段生成名称值时,将代码更改为替换1而不是0

The below code should work fine. 以下代码应该可以正常工作。

$(document).ready(function () {

    $('.add-button').click(function() {

        var count = $("tr.contacts-record").length;
        var template = $('.contacts-record-template').clone();
        template.find('input[type=text]').val(null);
        template.find('input[type=checkbox]').prop('checked', false);
        $.each(template.find('input[type=text]'), function() {
            var name = $(this).attr('name');             
            name = name.replace('1', count);             
            $(this).attr('name', name);
        });

        $('.list-Contacts').append(template);
        template.removeClass('contacts-record-template')
                                           .addClass('contacts-record').show();
    });
});

Your javascript runs on document ready. 您的javascript在文档准备就绪时运行。

please try: 请试试:

<input type="button" class="add-button" name="add" value="Add" />

switched to: 切换到:

<button type="button" class="add-button" onclick="doIt();" name="add">Add</button>

also main function: 主要功能:

function doIt() {
        var count = 0;
            count++;
            var template = $('.contacts-record-template').clone()
            template.find('input[type=text]').val(null);
            template.find('input[type=checkbox]').prop('checked', false);
            $.each(template.find('input[type=text]'), function () {
                var name = $(this).attr('name');
                name = name.replace('0', count - 1);
                $(this).attr('name', name);
            });

            $('.list-Contacts').append(template);
            template.removeClass('contacts-record-template').addClass('contacts-record').show();
    }

i hope its works. 我希望它的作品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM