locked
Dynamically Add/Delete Rows in HTLM Table RRS feed

  • Question

  • User-1244692504 posted

    I will appreciate your professional solution to the challenge of Adding/Deleting rows dynamically from HTML Table. I have implemented the addRow successfully and removing the last Row. However, if I have 20 items in the table and I want to remove item number 2, I will remove the last 18 items first before getting to the item required from removal. This is quite burdensome and time-wasting.

    Models

       public class ClientViewModel
        {
            public Underwriting_Client Underwriting_Client { get; set; }
            public IList<Underwriting_ClientContact> Underwriting_ClientContact { get; set; }
        } 
    
            public class Underwriting_Client
            {
                public string ClientCode { get; set; }
                [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
                public DateTime? DateOpen { get; set; }
                public string Title { get; set; }
                public string Name { get; set; }
                public string Occupation { get; set; }
                public string Address { get; set; }
                public string ModifiedBy { get; set; }
                public Int64 RowVersionNo2 { get; set; }
            }
    
        public class Underwriting_ClientContact
        {
            public string ClientCode { get; set; }
            public string ContactTitle { get; set; }
            public string ContactFullName { get; set; }
            public string ContactDesignation { get; set; }
            public string ContactPhoneNumber { get; set; }
            public string ContactEmailAddress { get; set; }
            public string ModifiedBy { get; set; }
            public Int64 RowVersionNo2 { get; set; }
            [IdentityPrimaryKey()]
            public int RecordID { get; set; }
    	public bool CheckBox {get; set; }
        }

    The two tables were related through the ClientCode.

    Controller - GET and POST

          [HTTPGET]
            public ActionResult CreateClient()
            {
                var viewModel = new ClientViewModel();
                viewModel.Underwriting_Client = new Underwriting_Client();
    
    	    viewModel.Underwriting_ClientContact = new List<Underwriting_ClientContact>();
                viewModel.Underwriting_ClientContact.Add(new Underwriting_ClientContact() { ClientCode = " ", ContactTitle = " ", ContactFullName = " ", ContactDesignation = " ", ContactPhoneNumber = " ", ContactEmailAddress = " " });
    	}
    
    
     	[HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult CreateClient(ClientViewModel model)
            {
                if (ModelState.IsValid)
                {
                    ValidationStateDictionary states = new ValidationStateDictionary();
    
                    _undewritingSetupService.AddClient(model, ref states);
     	    else
                {
                    Danger(Constants.Messages.ErrorNotice, true);
                    return View(model);
                }
            }

    View - Main/Parent View

    @model Brokerage.Model.ClientViewModel
    @section maincontent {
        @using (Html.BeginForm(CreateClient, "UnderwritingSetup", FormMethod.Post))
        {
          @Html.AntiForgeryToken()
    
        <div class="container-fluid " style="background:#e8c8d8; border-radius:8px;">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="row">
                <div class="form-group">
                    <div class="col-xs-2">
                        <span class="label label-danger col-xs-12">*All fields are required</span>
                    </div>
                </div>
                <br />
                <div class="row" style="margin:0px;">
                    <div class="col-md-12 col-sm-12 col-xs-12">
                        <div class=" form-group">
                            @Html.LabelFor(model => model.Underwriting_Client.Title, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                <div data-tip="Please enter the client's title, 'CORP' for Corporate">
                                    @Html.EditorFor(model => model.Underwriting_Client.Title, new { htmlAttributes = new { @class = "form-control input-sm", @onkeyup = "InputToUpper(this);", placeholder = "Enter the client's title" } })
                                    @Html.ValidationMessageFor(model => model.Underwriting_Client.Title, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12 col-sm-12 col-xs-12">
                        <div class=" form-group">
                            @Html.LabelFor(model => model.Underwriting_Client.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                <div data-tip="Please enter the client's name">
                                    @Html.EditorFor(model => model.Underwriting_Client.Name, new { htmlAttributes = new { @class = "form-control input-sm", @onkeyup = "InputToUpper(this);", placeholder = "Enter the client's name" } })
                                    @Html.ValidationMessageFor(model => model.Underwriting_Client.Name, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>
                    </div>
                    <br />
                    <div class="col-md-12 col-sm-12 col-xs-12">
                        <div class="form-group">
                            @Html.LabelFor(model => model.Underwriting_Client.Address, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                <div data-tip="Please enter the client's address">
                                    @Html.EditorFor(model => model.Underwriting_Client.Address, new { htmlAttributes = new { @class = "form-control input-sm", @onkeyup = "InputToUpper(this);", placeholder = "Enter the client's address" } })
                                    @Html.ValidationMessageFor(model => model.Underwriting_Client.Address, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>
                    </div>
                    <br />
    		<div class="col-md-12 col-sm-12 col-xs-12">
                        <div class="form-group">
                            @Html.LabelFor(model => model.Underwriting_Client.Address, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                <div data-tip="Please enter the client's address">
                                    @Html.EditorFor(model => model.Underwriting_Client.Address, new { htmlAttributes = new { @class = "form-control input-sm", @onkeyup = "InputToUpper(this);", placeholder = "Enter the client's address" } })
                                    @Html.ValidationMessageFor(model => model.Underwriting_Client.Address, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>
                    </div>
                    <br />
                    <div class="col-md-12 col-sm-12 col-xs-12">
                        <div class="form-group">
                            @Html.LabelFor(model => model.Underwriting_Client.Occupation, htmlAttributes: new { @class = "control-label col-md-2" })
                            <div class="col-md-10">
                                <div data-tip="Please enter the client's occupation">
                                    @Html.EditorFor(model => model.Underwriting_Client.Occupation, new { htmlAttributes = new { @class = "form-control input-sm", @onkeyup = "InputToUpper(this);", placeholder = "Enter the client's occupation" } })
                                    @Html.ValidationMessageFor(model => model.Underwriting_Client.Occupation, "", new { @class = "text-danger" })
                                </div>
                            </div>
                        </div>
                    </div>
    
     		<div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Create" class="form-control btn btn-primary" />
    			<a href="#showDialog" class="btn btn-primary" title="Corporate Client Contact" data-toggle="modal" data-id="" , style="float:right;">Client Contact</a>
                        </div>
                    </div>
    	}


    Modal "#showDialog" View

    Modal View - #showDialog
    
    <div class="row">
            <div class="col-md-12 col-sm-8 col-xs-12 col-xs-offset-0">
                <div id="showDialog" tabindex="-1" role="dialog" aria-labelledby="showDialogLabel" aria-hidden="true" class="modal fade">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                                <h4 class="modal-title" id="showDialogLabel">Client Contact Details</h4>
                            </div>
                            <div class="modal-body">
                                <hr />
                                <input type="submit" class="btn btn-primary" value="Add New Row" onclick="addRow('requestClientContacts'); return false;" />
                                <input type="submit" class="btn btn-primary" value="Remove Last Row" onclick="removeRow('requestClientContacts'); return false;" />
    			    <input type="submit" class="btn btn-primary" value="Delete Row" onclick="deleteRow('requestClientContacts'); return false;" />
                                <hr />
                                <div class="table-responsive">
                                    <table id="requestClientContacts" class="table table-bordered table-striped table-hover" cellspacing="0">
                                        <thead style=" background-color:#89006e !important; color:#fff;font-weight:bold;">
                                            <tr>
                                                <td>ClientCode</td>
                                                <td>Title</td>
                                                <td>Full Name</td>
                                                <td>Designation</td>
                                                <td>Phone Number</td>
                                                <td>Email Address</td>
    					    <td>Delete</td>
                                            </tr>
                                        </thead>
                                        @{if (!string.IsNullOrEmpty(Model.Underwriting_Client.ClientCode))
                                        {
                                            var prefx4 = "Underwriting_ClientContact";
                                            var prefx6 = prefx4 + ".index";
                                            for (var i = 1; i <= Model.Underwriting_ClientContact.Count; i++)
                                            {
                                                var itemIndex3 = string.Format("X{0}", i);
    
                                                var n7 = string.Format("{1}[X{0}].ClientCode", i, prefx4);
                                                var n8 = string.Format("{1}[X{0}].ContactTitle", i, prefx4);
                                                var n9 = string.Format("{1}[X{0}].ContactFullName", i, prefx4);
                                                var n10 = string.Format("{1}[X{0}].ContactDesignation", i, prefx4);
                                                var n11 = string.Format("{1}[X{0}].ContactPhoneNumber", i, prefx4);
                                                var n12 = string.Format("{1}[X{0}].ContactEmailAddress", i, prefx4);
    					    var n12 = string.Format("{1}[X{0}].ContactCheckBox", i, prefx4);
                                                <tr>
                                                    <td>
                                                        <input type="hidden" name="@prefx6" value="@itemIndex3" />
                                                        @Html.Hidden(n7, Model.Underwriting_ClientContact[i - 1].ClientCode, new { id = n7 })
    
                                                        @Html.TextBox(n8, Model.Underwriting_ClientContact[i - 1].ContactTitle, new { id = n8, @class = "form-control input-sm", @style = "width: 150px;" })
                                                        @Html.ValidationMessage(n8, "", new { @class = "text-danger" })
    
                                                        @Html.TextBox(n9, Model.Underwriting_ClientContact[i - 1].ContactFullName, new { id = n9, @class = "form-control input-sm", @style = "width: 350px;" })
                                                        @Html.ValidationMessage(n9, "", new { @class = "text-danger" })
    
                                                        @Html.TextBox(n10, Model.Underwriting_ClientContact[i - 1].ContactDesignation, new { id = n10, @class = "form-control input-sm", @style = "width: 350px;" })
                                                        @Html.ValidationMessage(n10, "", new { @class = "text-danger" })
    
                                                        @Html.TextBox(n11, Model.Underwriting_ClientContact[i - 1].ContactPhoneNumber, new { id = n11, @class = "form-control input-sm", @style = "width: 350px;" })
                                                        @Html.ValidationMessage(n11, "", new { @class = "text-danger" })
    
                                                        @Html.TextBox(n12, Model.Underwriting_ClientContact[i - 1].ContactEmailAddress, new { id = n12, @class = "form-control input-sm", @style = "width: 350px;" })
                                                        @Html.ValidationMessage(n12, "", new { @class = "text-danger" })
    
                                                        @Html.CheckBox(n13, Model.Underwriting_ClientContact[i - 1].ContactCheckBox, new { id = n13, @class = "form-control input-sm", @style = "width: 150px;" })
                                                        @Html.ValidationMessage(n13, "", new { @class = "text-danger" })
    
                                                    </td>
    
                                                </tr>
                                            }
                                        }
                                        else
                                        {
                                            int c = 1;
                                            foreach (var module in Model.Underwriting_ClientContact)
                                            {
                                                Html.RenderPartial("ClientContactDistributionEditor", module, new ViewDataDictionary(ViewData) {
    		                                             {"prefix", "Underwriting_ClientContact"}, {"itemIndex", "X" + c}
    		                                             });
                                                c = c + 1;
                                            }
                                        }
                                        }
                                    </table>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-primary" data-dismiss="modal">Next</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    AddRow(), RemoveRow() Javascripts functions are working well, but DeleteRow() is not working. 

    The Logic behind the DeleteRow() is the CheckBox. Every item checked or selected should be removed when the DeleteRow() is clicked.

    I have tried everything known to make it work, but's not responding to the onClick event. 

    Your assistance will be greatly appreciated.

    Partial View - ClientContactDistributionEditor

    @using Brokerage.Utility;
    @model Brokerage.Model.Underwriting_ClientContact
    <tr>
        @{var prefx2 = @ViewData["prefix"] + ".index";}
        @{var itIndex2 = @ViewData["itemIndex"];}
    
        @{var fieldPrefix = string.Format("{0}[{1}].", ViewData["prefix"], ViewData["itemIndex"]); }
        <td>
            <input type="hidden" name="@prefx2" value="@itIndex2" />
            <div class="form-group">
                @Html.Editor(fieldPrefix + "ClientCode", new { id = fieldPrefix + "ClientCode", @class = "form-control input-sm", @style = "width: 250px;", @readonly=true })
                @Html.ValidationMessage(fieldPrefix + "ClientCode", "", new { @class = "text-danger" })
            </div>
        </td>
        <td>
            @Html.Editor(fieldPrefix + "ContactTitle", new { id = fieldPrefix + "ContactTitle", @class = "form-control input-sm", @style = "width: 250px;" })
            @Html.ValidationMessage(fieldPrefix + "ContactTitle", "", new { @class = "text-danger" })
        </td>
        <td>
            @Html.Editor(fieldPrefix + "ContactFullName", new { id = fieldPrefix + "ContactFullName", @class = "form-control input-sm", @style = "width: 250px;" })
            @Html.ValidationMessage(fieldPrefix + "ContactFullName", "", new { @class = "text-danger" })
        </td>
         <td>
            @Html.Editor(fieldPrefix + "ContactDesignation", new { id = fieldPrefix + "ContactDesignation", @class = "form-control input-sm", @style = "width: 250px;" })
            @Html.ValidationMessage(fieldPrefix + "ContactDesignation", "", new { @class = "text-danger" })
        </td>
        <td>
            @Html.Editor(fieldPrefix + "ContactPhoneNumber", new { id = fieldPrefix + "ContactPhoneNumber", @class = "form-control input-sm", @style = "width: 250px;" })
            @Html.ValidationMessage(fieldPrefix + "ContactPhoneNumber", "", new { @class = "text-danger" })
        </td>
        <td>
            @Html.Editor(fieldPrefix + "ContactEmailAddress", new { id = fieldPrefix + "ContactEmailAddress", @class = "form-control input-sm", @style = "width: 250px;" })
            @Html.ValidationMessage(fieldPrefix + "ContactEmailAddress", "", new { @class = "text-danger" })
        </td>
    <td>
    @Html.CheckBox(fieldPrefix + "ContactCheckBox", new { id = fieldPrefix + "ContactCheckBox", @class = "form-control input-sm", @style = "width: 150px;" })
    @Html.ValidationMessage(fieldPrefix + "ContactCheckBox", "", new { @class = "text-danger" })
    </td>

    </tr>

    JavaScripts 

    <script type="text/javascript">
    function addRow(tableID) { var table = document.getElementById(tableID); //var rowZeroId = table.rows[0].id; var rowCount = table.rows.length; var row = table.insertRow(rowCount); row.id = "X" + rowCount; var colCount = table.rows[1].cells.length; for (var i = 0; i < colCount; i++) { var newcell = row.insertCell(i); newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(/X1/g, row.id); switch (newcell.childNodes[0].type) { case "text": newcell.childNodes[0].value = ""; break; case "checkbox": newcell.childNodes[0].checked = false; break; case "select-one": newcell.childNodes[0].selectedIndex = 0; break; case "hidden": newcell.childNodes[0].value = ""; break; } } } function removeRow(tableID) { var tbl = document.getElementById(tableID); var lastRow = tbl.rows.length; if (lastRow > 2) tbl.deleteRow(lastRow - 1); } function deleteRow(tableID) { try { var table = document.getElementById(tableID); var rowCount = table.rows.length; for (var i = 0; i < rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if (null != chkbox && true == chkbox.checked) { if (rowCount <= 1) { alert("Cannot delete all the rows."); break; } table.deleteRow(i); rowCount--; i--; } } } catch (e) { alert(e); } }

    What am I doing wrongly, please?

    Thank you all in anticipation of your quick response.

    Tuesday, August 4, 2020 1:38 PM

Answers

  • User1686398519 posted

    Hi Lawrence_Ajayi,

    1. Error "TypeError: Cannot read property 'checked' of null"  P
      • If you still want to use your original code, please refer to the modified code below.
      •   function addRow(tableID) {
                //The code here has not been modified, so it is omitted.
                var index = table.rows[rowCount - 1].id;
                index = Number(index);
                if (index == 0) {
                    row.id = index + 2;
                } else {
                    row.id = index + 1;
                }
                var x = "X" + row.id;
                var colCount = table.rows[1].cells.length;
        //The code here has not been modified, so it is omitted.
        newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(/X1/g, x); //The code here has not been modified, so it is omitted. } function deleteRow(tableID) {
        //The code here has not been modified, so it is omitted. var index = table.rows[rowCount - 1].id;
                index = Number(index);
                if (rowCount <= 2) { alert("<=2");
                     BootstrapDialog.alert("cannot delete all rows");
                } else {
                 for (var i = index; i >1; i--) {
        //The code here has not been modified, so it is omitted.
        if (c != null) {
                      if (c.checked) {
                          c.closest("tr").remove();
                      }
                  }
        //The code here has not been modified, so it is omitted. }
    2. If you want to use "BootstrapDialog.alert", you must quote the "bootstrap-dialog.js" and "bootstrap-dialog.css" files.
      • You can install bootstrap-dialog through Nuget.
    3. For you want to dynamically add and delete table elements, I suggest you use jquery, which is easier. If you are willing to try, please refer to the example below.
    4. Please I would like to know if I could use this logic to implement the File upload
      • You can use similar logic to dynamically add input for uploading files.
    5. how do I modify the HTML table with the PartialView to accommodate the file upload?. Both HTTP GET and HTTP POST.
      • Do you want to dynamically add partial views to the table?If this is the case, you can combine ajax and partial views to achieve your needs.

    Note: There is a small suggestion. If you have a new question, you can submit a new post, which can help you better.

    Use jquery

    <div class="row">
       @*The code here has not been modified, so it is omitted.*@
       <button id="JQuerytest-AddRow">JQuerytest-AddRow</button>
       <button id="JQuerytest-RemoveRow">JQuerytest-RemoveRow</button>
       <button id="JQuerytest-RemoveLastRow">JQuerytest-RemoveLastRow</button>
       @*The code here has not been modified, so it is omitted.*@
    </div>
    <link href="~/Content/bootstrap-dialog.css" rel="stylesheet" />
    @section scripts{
        <script src="~/Scripts/bootstrap-dialog.js"></script>
        <script>
            $("#JQuerytest-AddRow").click(function () {
                var clonedRow = $("#requestClientContacts tbody tr:first").clone();
                clonedRow.find('input').val('');
                clonedRow.find("input[type=checkbox]").attr("checked", false);
                $('#requestClientContacts tbody').append(clonedRow);
            });
            $("#JQuerytest-RemoveLastRow").click(function () {
                var count = $("#requestClientContacts tbody tr").length;
                if (count > 1) {
                    var clonedRow = $("#requestClientContacts tbody tr:last").remove();
                } else {
                    BootstrapDialog.alert("cannot delete all rows");
                }
            });
            $("#JQuerytest-RemoveRow").click(function () {
                var table = $("#requestClientContacts");
    
                //Annotated code implementation: the first line cannot be deleted
    
                //if (table.find("tbody tr:first").find("input[type=checkbox]").is(":checked")) {
                //    BootstrapDialog.alert("cannot delete all rows");
                //}
                //table.find("tbody tr:not(:first)").each(function () {
                //    if ($(this).find("input[type=checkbox]").is(":checked")) {
                //        $(this).remove();
                //    }
                //});
    
                //this cod:at least one must exist.
                var count = table.find("tbody tr").length;
                var selectcount =0;
                table.find("tbody tr").each(function () {
                    if ($(this).find("input[type=checkbox]").is(":checked")) {
                        selectcount++;
                    }
                });
                if (selectcount == count) {
                    BootstrapDialog.alert("cannot delete all rows");
                } else {
                    table.find("tbody tr").each(function () {
                        if ($(this).find("input[type=checkbox]").is(":checked")) {
                            $(this).remove();
                        }
                    });
                }
            });
          
      </script>
    }

    Here is the result.

    Best regards,

    Yihui Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 6, 2020 10:02 AM

All replies

  • User-474980206 posted

    If you are going to loop thru an array and delete entries, you need to loop backwards, from the last index to the first.

    Tuesday, August 4, 2020 2:35 PM
  • User1686398519 posted

    Hi Lawrence_Ajayi,

    Your delete function did not get the checkbox correctly. You can get elements by name or id and delete them. Below is the solution I gave, please refer to it.

    function deleteRow(tableID) {
       try {
              var table = document.getElementById(tableID);
              var rowCount = table.rows.length;
              for (var i = 1; i < rowCount; i++) {
                 var c = document.getElementById("Underwriting_ClientContact[X" + i + "].ContactCheckBox");
                 if (c.checked) {
                     c.closest("tr").remove();
                 }
              }
           } catch (e) {
                alert(e);
           }
    }

    Here is the result.

    Best regards,

    Yihui Sun

    Wednesday, August 5, 2020 7:29 AM
  • User-1244692504 posted

    function deleteRow(tableID) {
       try {
              var table = document.getElementById(tableID);
              var rowCount = table.rows.length;
              for (var i = 1; i < rowCount; i++) {
                 var c = document.getElementById("Underwriting_ClientContact[X" + i + "].ContactCheckBox");
                 if (c.checked) {
                     c.closest("tr").remove();
                 }
              }
           } catch (e) {
                alert(e);
           }
    }

    Thank you for your kind assistance. I have amended the Javascript code. However, I would love to include a Bootstrap alert to restrict the system from deleting all the rows. as shown in the code below - it's not responding as I wanted, please I need your assistant. 

           function deleteRow(tableID) {
                try {
                    var table = document.getElementById(tableID);
                    var rowCount = table.rows.length;
                    for (var i = 1; i < rowCount; i++) {
                        var c = document.getElementById("Underwriting_ClientContact[X" + i + "].ContactCheckBox");
                        if (c.checked) {
                        
                            if (rowCount <= 1)
                            {
                                BootstrapDialog.alert("Cannot delete all the rows.");
                                break;
                            }
                        c.closest("tr").remove();
                       }
                    }
                } catch (e) {
                    BootstrapDialog.alert(e);
                }
            }

    Again, it deleted successfully once, after which if you want to delete again on the same page without refreshing the page, it will display the 

    Error "TypeError: Cannot read property 'checked' of null"  Please what causes this error? and how do I resolve it ?

    In addition, if the user marks all for deletion, the system should reject the request or deduct one row(- 1 row) from the rowCount.

    Your Advice:

    1. Please I would like to know if I could use this logic to implement the File upload as the user can determine how many files upload he needs to add, rather than the static 9 rows under the ARRAY logic. My concern is that, If the user needed more than 9 file uploads, it will result in the code amendment again.

    2. Will the HttpPostedFileBase works with the HTML table, and if yes, how do I modify the HTML table with the PartialView to accommodate the file upload?. Both HTTP GET and HTTP POST.

    You are greatly appreciated, brother.

     Best regards

    Wednesday, August 5, 2020 5:49 PM
  • User1686398519 posted

    Hi Lawrence_Ajayi,

    1. Error "TypeError: Cannot read property 'checked' of null"  P
      • If you still want to use your original code, please refer to the modified code below.
      •   function addRow(tableID) {
                //The code here has not been modified, so it is omitted.
                var index = table.rows[rowCount - 1].id;
                index = Number(index);
                if (index == 0) {
                    row.id = index + 2;
                } else {
                    row.id = index + 1;
                }
                var x = "X" + row.id;
                var colCount = table.rows[1].cells.length;
        //The code here has not been modified, so it is omitted.
        newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(/X1/g, x); //The code here has not been modified, so it is omitted. } function deleteRow(tableID) {
        //The code here has not been modified, so it is omitted. var index = table.rows[rowCount - 1].id;
                index = Number(index);
                if (rowCount <= 2) { alert("<=2");
                     BootstrapDialog.alert("cannot delete all rows");
                } else {
                 for (var i = index; i >1; i--) {
        //The code here has not been modified, so it is omitted.
        if (c != null) {
                      if (c.checked) {
                          c.closest("tr").remove();
                      }
                  }
        //The code here has not been modified, so it is omitted. }
    2. If you want to use "BootstrapDialog.alert", you must quote the "bootstrap-dialog.js" and "bootstrap-dialog.css" files.
      • You can install bootstrap-dialog through Nuget.
    3. For you want to dynamically add and delete table elements, I suggest you use jquery, which is easier. If you are willing to try, please refer to the example below.
    4. Please I would like to know if I could use this logic to implement the File upload
      • You can use similar logic to dynamically add input for uploading files.
    5. how do I modify the HTML table with the PartialView to accommodate the file upload?. Both HTTP GET and HTTP POST.
      • Do you want to dynamically add partial views to the table?If this is the case, you can combine ajax and partial views to achieve your needs.

    Note: There is a small suggestion. If you have a new question, you can submit a new post, which can help you better.

    Use jquery

    <div class="row">
       @*The code here has not been modified, so it is omitted.*@
       <button id="JQuerytest-AddRow">JQuerytest-AddRow</button>
       <button id="JQuerytest-RemoveRow">JQuerytest-RemoveRow</button>
       <button id="JQuerytest-RemoveLastRow">JQuerytest-RemoveLastRow</button>
       @*The code here has not been modified, so it is omitted.*@
    </div>
    <link href="~/Content/bootstrap-dialog.css" rel="stylesheet" />
    @section scripts{
        <script src="~/Scripts/bootstrap-dialog.js"></script>
        <script>
            $("#JQuerytest-AddRow").click(function () {
                var clonedRow = $("#requestClientContacts tbody tr:first").clone();
                clonedRow.find('input').val('');
                clonedRow.find("input[type=checkbox]").attr("checked", false);
                $('#requestClientContacts tbody').append(clonedRow);
            });
            $("#JQuerytest-RemoveLastRow").click(function () {
                var count = $("#requestClientContacts tbody tr").length;
                if (count > 1) {
                    var clonedRow = $("#requestClientContacts tbody tr:last").remove();
                } else {
                    BootstrapDialog.alert("cannot delete all rows");
                }
            });
            $("#JQuerytest-RemoveRow").click(function () {
                var table = $("#requestClientContacts");
    
                //Annotated code implementation: the first line cannot be deleted
    
                //if (table.find("tbody tr:first").find("input[type=checkbox]").is(":checked")) {
                //    BootstrapDialog.alert("cannot delete all rows");
                //}
                //table.find("tbody tr:not(:first)").each(function () {
                //    if ($(this).find("input[type=checkbox]").is(":checked")) {
                //        $(this).remove();
                //    }
                //});
    
                //this cod:at least one must exist.
                var count = table.find("tbody tr").length;
                var selectcount =0;
                table.find("tbody tr").each(function () {
                    if ($(this).find("input[type=checkbox]").is(":checked")) {
                        selectcount++;
                    }
                });
                if (selectcount == count) {
                    BootstrapDialog.alert("cannot delete all rows");
                } else {
                    table.find("tbody tr").each(function () {
                        if ($(this).find("input[type=checkbox]").is(":checked")) {
                            $(this).remove();
                        }
                    });
                }
            });
          
      </script>
    }

    Here is the result.

    Best regards,

    Yihui Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 6, 2020 10:02 AM
  • User-1244692504 posted

    Thank you so much for your professionalism and your time to guide me through. You are highly appreciated.

    The Jquery scripts and demo were quite useful and appropriate for my application requirement. it uses less code and quite flexible to adapt.

     I have replaced the JavaScript code with the Jquery and it works great!

    Thanks a million. 

    Kind regards

    Lawrence 

    Thursday, August 6, 2020 8:17 PM