Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add rows in ASP.NET MVC table form

I'm trying to program an "add" button below an ASP.NET MVC table to dynamically append a blank row, and then have a submit button to save each row to the database with one click.

There are several similar questions on SO but none that I have been able to apply to this. I've been trying to apply this example but the "add" button is not appending new rows.

Model:

public class TableForm
    {
        public int Id { get; set; }
        public List<TableFormData> TableFormDatas { get; set; }
    }

    public class TableFormData
    {
        public int Id { get; set; }
        public string ClientSampleID { get; set; }
        public string AdditionalComments { get; set; }
        public string AcidStables { get; set; }

Razor view:

@model NewTestSix.Models.TableForm

@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

<fieldset>
    <legend>Sample submission</legend>
    <table id="submissionTable" class="table table-bordered">
        <thead>
            <tr>
                <td>Sample ID</td>
                <td>Additional Comments</td>
                <td>Acid-stable amino acids</td>
            </tr>
        </thead>

        <tr id="tablerow0">
            <td>
                <div class="editor-field">
                    <input class="text-box single-line" name="ClientSampleID[0]" type="text" value="" required="required" />
                </div>
            </td>
            <td>
                <div class="editor-field">
                    <input class="text-box single-line" name="AdditionalComments[0]" type="text" value="" required="required" />
                </div>
            </td>
            <td>
                <div class="editor-field">
                    <input class="text-box single-line" name="AcidStables[0]" type="text" value="" />
                </div>
            </td>
            <td>
                <button type="button" class="btn btn-primary" onclick="removeTr(0);">Delete</button>
            </td>
            <td>

            </td>
        </tr>

    </table>
    <p>
        <button id="add" type="submit" class="btn btn-primary">Add</button>
    </p>
    <hr />

    <p>
        <input type="submit" value="Create" class="btn btn-default" />
    </p>
</fieldset>
}

@section Scripts {
    <script src="~/bundles/jqueryval.js" type="text/javascript">
        var counter = 1;
        $(function () {

            $('#add').click(function () {
                $('<tr id="tablerow' + counter + '"><td>' +
                    '<input type="text" class="text-box single-line" name="ClientSampleID[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" class="text-box single-line" name="AdditionalComments[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" class="text-box single-line" name="AcidStables[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<button type="button" class="btn btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
                    '</td>' +
                    '</tr>').appendTo('#submissionTable');
                counter++;
                return false;
            });
        });
        function removeTr(index) {
            if (counter > 1) {
                $('#tablerow' + index).remove();
                counter--;
            }
            return false;
        }
    </script>

I'm not too fussed about model binding with the controller at this stage, I just want to get this add button working. example controller:

  [HttpPost]
        public ActionResult Index(string any = "")
        {
            IList<TableForm> _TableForm = new List<TableForm>();

            //Loop through the forms
            for (int i = 0; i <= Request.Form.Count; i++)
            {
                var ClientSampleID = Request.Form["ClientSampleID[" + i + "]"];
                var additionalComments = Request.Form["AdditionalComments[" + i + "]"];
                var acidStables = Request.Form["AcidStables[" + i + "]"];

                if (!String.IsNullOrEmpty(ClientSampleID))
                {
                    _TableForm.Add(new TableForm { ClientSampleID = ClientSampleID, AcidStables = acidStables, AdditionalComments = additionalComments });
                }
            }

            return View();
        }

Thanks for any insights.

Current: current

Desired after clicking "add" button: enter image description here

like image 887
heds1 Avatar asked May 11 '19 04:05

heds1


1 Answers

Change your

<button id="add" type="submit" class="btn btn-primary">Add</button>

into

<button id="add" type="button" class="btn btn-primary">Add</button>

...as I don't think the "Add" button should ever make the browser do a form submission when clicked, it should only invoke your button's client-side 'click' event-handler.

Then remove src="~/bundles/jqueryval.js" part from your script element's opening tag: inline scripts cannot have a src="" attribute.

Like this:

<script type="text/javascript">
    var counter = 1;
    //... the rest of your code is here...
</script>

If you actually have a jqueryval.js file, put it in another <script> tag.

Here is the result you are expecting if I'm not mistaken.

var counter = 1;
        $(function () {
            $('#add').click(function () {
                $('<tr id="tablerow' + counter + '"><td>' +
                    '<input type="text" class="text-box single-line" name="ClientSampleID[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" class="text-box single-line" name="AdditionalComments[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<input type="text" class="text-box single-line" name="AcidStables[' + counter + ']" value="" required="required" />' +
                    '</td>' +
                    '<td>' +
                    '<button type="button" class="btn btn-primary" onclick="removeTr(' + counter + ');">Delete</button>' +
                    '</td>' +
                    '</tr>').appendTo('#submissionTable');
                counter++;
                return false;
            });
        });
        function removeTr(index) {
            if (counter > 1) {
                $('#tablerow' + index).remove();
                counter--;
            }
            return false;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
        <legend>Sample submission</legend>
        <table id="submissionTable" class="table table-bordered">
            <thead>
                <tr>
                    <td>Sample ID</td>
                    <td>Additional Comments</td>
                    <td>Acid-stable amino acids</td>
                </tr>
            </thead>

            <tr id="tablerow0">
                <td>
                    <div class="editor-field">
                        <input class="text-box single-line" name="ClientSampleID[0]" type="text" value="" required="required" />
                    </div>
                </td>
                <td>
                    <div class="editor-field">
                        <input class="text-box single-line" name="AdditionalComments[0]" type="text" value="" required="required" />
                    </div>
                </td>
                <td>
                    <div class="editor-field">
                        <input class="text-box single-line" name="AcidStables[0]" type="text" value="" />
                    </div>
                </td>
                <td>
                    <button type="button" class="btn btn-primary" onclick="removeTr(0);">Delete</button>
                </td>
                <td></td>
            </tr>

        </table>
        <p>
            <button id="add" type="button" class="btn btn-primary">Add</button>
        </p>
        <hr />

        <p>
            <input type="submit" value="Create" class="btn btn-default" />
        </p>
    </fieldset>

Let me know if it helps.

like image 178
Nam Le Avatar answered Oct 07 '22 06:10

Nam Le