Save (Insert) dynamically added HTML Table rows in database in ASP.Net Core MVC

leila398
 
on Dec 06, 2021 09:52 PM
Sample_495477.zip
1874 Views

Hi,

I have a simple form to add to the database. Part of the form has this table, where rows can be added dynamically.

Question is, how do I add the contents of the addiitonal rows to the DB. Here is my code:

@model POSys.Data.InsertOrderVM

@{
    ViewData["Title"] = "Index";
}

<h1>Insert</h1>
<hr />
<br />
<br />
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <script>
        $(document).ready(function () {
            var counter = 0;
            $("#addrow").on("click", function () {
                var newRow = $("<tr>");
                var cols = "";
                cols += '<td><input type="text" class="form-control" name="Name' + counter + '"/></td>'
                cols += '<td><input type="text" class="form-control" name="Description' + counter + '"/></td>';
                cols += '<td><select id="Department" class="form-control">';
                cols += '<option selected="1">1</option>';
                cols += '<option value="2">2</option>';
                cols += '<option value="3">3</option>';
                cols += '</select></td >';
                cols += '<td><button type="button" class="ibtnDel btn btn-md btn-danger "><i class="fa fa-trash-o"></i></button></td>';
                newRow.append(cols);
                $("table.order-list").append(newRow);
                counter++;
            });

            $("table.order-list").on("click", ".ibtnDel", function (event) {
                $(this).closest("tr").remove();
                counter -= 1
            });
        });

    </script>
</head>
<body>
    <form asp-action="Create">
       <div class="container">
            <table id="myTable" class=" table order-list">
                <thead>
                    <tr>
                        <td>Item Name</td>
                        <td>Description</td>
                        <td>Department</td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td class="col-md-2">
                            <input asp-for="Item_Name" class="form-control" />
                            <span asp-validation-for="Item_Name" class="text-danger"></span>
                        </td>
                        <td class="col-lg-4">
                            <input asp-for="Description" class="form-control" />
                            <span asp-validation-for="Description" class="text-danger"></span>
                        </td>
                        <td class="col-md-2">
                            @Html.DropDownListFor(model => model.Department,
                         new List<SelectListItem> {
                              new SelectListItem { Value = "1" , Text = "1" },
                              new SelectListItem { Value = "2" , Text = "2" },
                              new SelectListItem { Value = "3" , Text = "3" },

                           }, "Select",
                         new { @class = "form-control" })
                        </td>                       
                        <td class="col-md-4">
                            <a class="deleteRow"></a>

                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="12">
                            <button type="button" id="addrow" class="btn btn-info add-new"><i class="fa fa-plus"></i>Add New Item</button>
                        </td>
                    </tr>
                    <tr>
                    </tr>
                </tfoot>
            </table>       
            <br />
            <hr />
            <div class="form-group">
                <input type="submit" value="Submit" class="btn btn-primary" />
            </div>
        </div>
    </form>
</body>
</html>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

At the moment it only adds the first row, the additional rows do not get added.

How can I add them as well?

Thanks

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 07, 2021 12:31 AM

Hi leila398,

You need to make ajax call to insert the record in database.

Refer below example.

Controller

public class HomeController : Controller
{
    // GET: Home
    public IActionResult Index()
    {
        return View();
    }

    public JsonResult InsertOrders(List<InsertOrderVM> orders)
    {
        foreach (InsertOrderVM order in orders)
        {
            // Code to insert record in database.
        }
        return Json(orders);
    }
}

View

@model Add_Table_Row_MVC.Models.InsertOrderVM

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Varela+Round|Open+Sans">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <script>
        $(document).ready(function () {
            var counter = 0;
            $("#addrow").on("click", function () {
                var newRow = $("<tr>");
                var cols = "";
                cols += '<td><input id="txtName" type="text" class="form-control" name="Name' + counter + '" /></td>'
                cols += '<td><input id="txtDescription" type="text" class="form-control" name="Description' + counter + '" /></td>';
                cols += '<td><select id="ddlDepartment" class="form-control" name="Department' + counter + '">';
                cols += '<option value="0" selected>Select</option>';
                cols += '<option value="1">Department 1</option>';
                cols += '<option value="2">Department 2</option>';
                cols += '<option value="3">Department 3</option>';
                cols += '</select></td >';
                cols += '<td><button type="button" class="ibtnDel btn btn-md btn-danger "><i class="fa fa-trash-o"></i></button></td>';
                newRow.append(cols);
                $("table.order-list").append(newRow);
                counter++;
            });

            $("table.order-list").on("click", ".ibtnDel", function (event) {
                $(this).closest("tr").remove();
                counter -= 1
            });

            $("#btnSubmit").on("click", function () {
                var insertOrderVM = new Array();
                $("table.order-list TBODY TR").each(function () {
                    var row = $(this);
                    var orders = {};
                    orders.Item_Name = row.find("[id*=txtName]").val();
                    orders.Description = row.find("[id*=txtDescription]").val();
                    orders.Department = row.find("[id*=ddlDepartment]").val();
                    insertOrderVM.push(orders);
                });
                $.ajax({
                    type: "POST",
                    url: "/Home/InsertOrders",
                    data: JSON.stringify(insertOrderVM),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        alert("Record(s) inserted.");
                    },
                    error: function (r) {
                        alert(r.responseText);
                    }
                });
            });

        });
    </script>
</head>
<body>
    <div class="container">
        <table id="myTable" class=" table order-list">
            <thead>
                <tr>
                    <td>Item Name</td>
                    <td>Description</td>
                    <td>Department</td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="col-md-2">
                        <input asp-for="Item_Name" class="form-control" id="txtName" />
                        <span asp-validation-for="Item_Name" class="text-danger"></span>
                    </td>
                    <td class="col-lg-4">
                        <input asp-for="Description" class="form-control" id="txtDescription" />
                        <span asp-validation-for="Description" class="text-danger"></span>
                    </td>
                    <td class="col-md-2">
                        @Html.DropDownListFor(model => model.Department,
                       new List<SelectListItem> {
                          new SelectListItem { Value = "1" , Text = "Department 1" },
                          new SelectListItem { Value = "2" , Text = "Department 2" },
                          new SelectListItem { Value = "3" , Text = "Department 3" }
                       }, "Select", new { @id = "ddlDepartment", @class = "form-control" })
                    </td>
                    <td class="col-md-4">
                        <a class="deleteRow"></a>

                    </td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="12">
                        <button type="button" id="addrow" class="btn btn-info add-new"><i class="fa fa-plus"></i>Add New Item</button>
                    </td>
                </tr>
                <tr></tr>
            </tfoot>
        </table>
        <br />
        <hr />
        <div class="form-group">
            <input id="btnSubmit" type="submit" value="Submit" class="btn btn-primary" />
        </div>
    </div>
</body>
</html>

 

dharmendr
 
on Dec 07, 2021 04:14 AM

Add [FromBody] attribute before the parameter.