locked
Save multi rows of dynamic HTML table to database using jquery, Json in MVC RRS feed

  • Question

  • User1618447750 posted

    Summary of the problem I am having:

    Hi, I need to save all the records in the HTML table to the database.

    Error I am receiving:

    In the controller: itemlist = null

    My code:

    The View: Create.cshtml

    @model FiltersReqSys.ViewModel.OrderOrderItemsListViewModel
    
    @{
        ViewBag.Title = "Create";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Create</h2>
    <h4>Order</h4>
    <h4>Here, you can add a new order.</h4>
    <hr />
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    
        <div class="container">
            <div class="form-horizontal">
                <div class="panel-body">
                    <!-- FIRST COLUMN -->
                    <div class="col-sm-6">
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.OrderDate, htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.TextBoxFor(model => model.Order.OrderDate, "{0:dd/MM/yyyy}", new { @class = "form-control", @id = "OrderDateId", @Value = System.DateTime.Now.ToShortDateString(), @readonly = "readonly" })
                                @Html.ValidationMessageFor(model => model.Order.OrderDate, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.RegionId, "Region", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("RegionId", null, htmlAttributes: new { @class = "form-control", @id = "RegionIdId" })
                                @Html.ValidationMessageFor(model => model.Order.RegionId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.DistrictId, "District", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("DistrictId", null, htmlAttributes: new { @class = "form-control", @id = "DistrictIdId" })
                                @Html.ValidationMessageFor(model => model.Order.DistrictId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.SupplierId, "Supplier", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("SupplierId", null, htmlAttributes: new { @class = "form-control", @id = "SupplierIdId" })
                                @Html.ValidationMessageFor(model => model.Order.SupplierId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                    </div>
    
                    <!-- SECOND COLUMN -->
                    <div class="col-sm-6">
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.FilterTypeId, "Filter Type", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("FilterTypeId", null, htmlAttributes: new { @class = "form-control", @id = "FilterTypeIdId" })
                                @Html.ValidationMessageFor(model => model.Order.FilterTypeId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.FilterListId, "Filter Part Number", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("FilterListId", null, htmlAttributes: new { @class = "form-control", @id = "FilterListIdId" })
                                @Html.ValidationMessageFor(model => model.Order.FilterListId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.FilterQuan, htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.EditorFor(model => model.Order.FilterQuan, new { htmlAttributes = new { @class = "form-control", @id = "FilterQuanId" } })
                                @Html.ValidationMessageFor(model => model.Order.FilterQuan, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
    
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.Note, htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.TextBoxFor(model => model.Order.Note, new { @class = "form-control", @id = "NoteId", @Value = "No Notes" })
                                @Html.ValidationMessageFor(model => model.Order.Note, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                    </div>
    
                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="button" value="Add New Row" class="btn btn-success" onclick="AddNew()" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    
    
        <table id="tbl" class="table table-hover">
            <thead>
                <tr>
    
                    <th>SN</th>
                    <th>Order Date</th>
                    <th>Region</th>
                    <th>District</th>
                    <th>FilterType</th>
                    <th>FilterPartNumber</th>
                    <th>Quantity</th>
                    <th>Supplier</th>
                    <th>Note</th>
                    <th>Action</th>
                </tr>
            </thead>
        </table>
    
        <div class="form-horizontal">
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-primary" id="btnInsert" />
                    @Html.ActionLink("Cancel or back to list", "Index", null, new { @class = "btn btn-default" })
                </div>
            </div>
        </div>
    
    }
    
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/JqueryDataTables")
    
        <script src="~/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
        <script>
            // Set the row number of the table
            function RowNum($t) {
                var c = 0;
                $t.find("tr").each(function (ind, el) {
                    $(el).find("td:eq(0)").html(c++);
    
                });
            }
    
            $(document).ready(function () {
    
                $("#tbl td input.rdelete").live("click", function () {
                    var srow = $(this).parent().parent();
                    srow.remove();
                    RowNum($("#tbl"));
                });
            });
    
            // Add new row to the table
            function AddNew() {
    
                var SN = SN;
                var OrderDate = $("#OrderDateId").val();
                var Region = $("#RegionIdId option:selected").text();
                var District = $("#DistrictIdId option:selected").text();
                var FilterType = $("#FilterTypeIdId option:selected").text();
                var FilterList = $("#FilterListIdId option:selected").text();
                var FilterQuan = $("#FilterQuanId").val();
                var Supplier = $("#SupplierIdId option:selected").text();
                var Note = $("#NoteId").val();
                var BtnDelete = "<input type=\"button\" value = \"Delete\" class=\"rdelete\"/>"
                var markup = "<tr><td>" + "</td><td>" + OrderDate + "</td><td>" + Region + "</td><td>" + District + "</td><td>" + FilterType + "</td><td>" + FilterList + "</td><td>" + FilterQuan + "</td><td>" + Supplier + "</td><td>" + Note + "</td><td>" + BtnDelete + "</td></tr>";
                $("#tbl tr:last").after(markup);
                RowNum($("#tbl"));
    
            }
    
            //Get all records from the table
            $(function () {
                $("#btnInsert").click(function () {
                    var itemlist = [];
    
                    //get cell values, instead of the header text.
                    $("tbl tr:not(:first)").each(function () {
                        var tdlist = $(this).find("tr");
                        var Item = {
                            FilterType: $(tdlist[4]).html(),
                            FilterPartNumber: $(tdlist[5]).html(),
                            Quantity: $(tdlist[6]).html(),
                            OrderId: 1
                        };
                        itemlist.push(Item);
                    })
    
                    $.ajax({
                        url: '@Url.Action("Create", "Orders")', //
                        dataType: "json",
                        data: JSON.stringify({ itemlist: itemlist }),
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (result) {
                            alert("success");
                        },
                        error: function (xhr) {
                            alert("error");
                        }
                    });
                });
            });
        </script>
    }
    
    

    The Controller: 

    [HttpPost]
    [ValidateAntiForgeryToken]
            public ActionResult Create(List<OrderItemsList> itemlist)
            {
                if (ModelState.IsValid)
                {
                    //var OrderItemList = new OrderItemsList();
    
    
                    foreach (var i in itemlist)
                    {
                        db.OrderItemsLists.Add(i);
                    }
    
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                return View(itemlist);
            }

    Monday, November 12, 2018 7:40 PM

All replies

  • User1520731567 posted

    Hi refa_karem,

    @model FiltersReqSys.ViewModel.OrderOrderItemsListViewModel

     $("tbl tr:not(:first)").each(function () {
                        var tdlist = $(this).find("tr");
                        var Item = {
                            FilterType: $(tdlist[4]).html(),
                            FilterPartNumber: $(tdlist[5]).html(),
                            Quantity: $(tdlist[6]).html(),
                            OrderId: 1
                        };
                        itemlist.push(Item);
                    })

       public ActionResult Create(List<OrderItemsList> itemlist)

    1.Does your field correspond to your model?

    2.In this step,Is itemlist Null?

      data: JSON.stringify({ itemlist: itemlist }),

    I suggest you could open F12 developer tool to check your code in front end.

    If you have any questions,please post more details,such as: OrderOrderItemsListViewModel, OrderItemsList...

    Best Regards.

    Yuki Tao

    Tuesday, November 13, 2018 6:20 AM
  • User1618447750 posted

    Hi Yuki Tao,

    • The following image is showing my application:
    • the user click "Add new row" to add his request to the HTML table then click "Create" to save all the records to the database.

    https://drive.google.com/open?id=1a70no7NvNOw0unEPBPvpqpnUEfuy0D_b

    My App

    • Yes, in this step: the "itemlist" = null
      data: JSON.stringify({ itemlist: itemlist }),
    • the Error in the controller

    https://drive.google.com/open?id=1vbGHKC0eKf6o_TOSduQaNZgqdtBZM-Mg

    Error

    Thanks for your support ...

    Tuesday, November 13, 2018 5:59 PM
  • User475983607 posted

    Missing the "#".

    $("tbl tr:not(:first)").each(function () {

    Should be 

    $("#tbl tr:not(:first)").each(function () {

    Please use the browser's dev tools (F12) to debug your code.

    Tuesday, November 13, 2018 6:08 PM
  • User1618447750 posted

    Hi mgebhard,

     Thanks for your suggestion. Unfortunately, not working. I'm facing the same error. 

    itemlist = null
    
    Tuesday, November 13, 2018 6:23 PM
  • User1618447750 posted

    Hi,

    Kindly, find the source code for my application.

    https://drive.google.com/open?id=19HVvecdTn9QS1CXo-AA5fAghCkRd-Cny

    Thanks ...

    Tuesday, November 13, 2018 6:44 PM
  • User475983607 posted

    Thanks for your suggestion. Unfortunately, not working. I'm facing the same error. 

    Making statements like "not working" give the appearance that you are not trying.  What does "not working" means.  After fixing the selector bug, does the code enter the each loop? 

    What troubleshooting steps have you performed? 

    See the following If you are new to debugging JavaScript.  Browser have a very rich debugging environment.

    https://developers.google.com/web/tools/chrome-devtools/

    https://developers.google.com/web/tools/chrome-devtools/javascript/

    Keep in mind it's much easier for you to debug your logic then for us to figure out the intent of the code.  

    Tuesday, November 13, 2018 6:46 PM
  • User475983607 posted

    Hi,

    Kindly, find the source code for my application.

    https://drive.google.com/open?id=19HVvecdTn9QS1CXo-AA5fAghCkRd-Cny

    Thanks ...

    Here's another bug...

                    //get cell values, instead of the header text.
                    $("tbl tr:not(:first)").each(function () {
                        var tdlist = $(this).find("tr");
                        var Item = {
                            FilterType: $(tdlist[4]).html(),
                            FilterPartNumber: $(tdlist[5]).html(),
                            Quantity: $(tdlist[6]).html(),
                            OrderId: 1
                        };
                        itemlist.push(Item);
                    })

    Try something like this...

    var itemlist = [];
    $("#tbl tr:not(:first)").each(function () {
        itemlist.push({
            FilterType: $(this).find(':nth-child(4)').text(),
            FilterPartNumber: $(this).find(':nth-child(5)').text(),
            Quantity: $(this).find(':nth-child(6)').text(),
            OrderId: 1
        });
    });
    console.log(itemlist);

    Tuesday, November 13, 2018 7:16 PM
  • User1520731567 posted

    Hi refa_karem,

    I try to test your code,modify and work fine,

    2.In this step,Is itemlist Null?

    Firstly, in front end,I find your click event can not run,you should delete Initialization function:

    $(function () {})

    1.Does your field correspond to your model?

    And I suggest you should set the name same with your model.

    You could refer to my code:

      //$(function () {
                $("#btnInsert").click(function () {
                    var itemlist = [];
    
                    //get cell values, instead of the header text.
                    $("#tbl tr:not(:first)").each(function () {
                        var tdlist = $(this).find("tr");
                        var Item = {
                            //FilterType: $(tdlist[4]).html(),
                            //FilterPartNumber: $(tdlist[5]).html(),
                            //Quantity: $(tdlist[6]).html(),
                            //OrderId: 1
                            FilterType: $(this).find(':nth-child(4)').text(), //fields same with OrderItemsList model
                            FilterPN: $(this).find(':nth-child(5)').text(),
                            FilterQuan: $(this).find(':nth-child(6)').text(),
                            OrderId: 1
                        };
    
    
                        itemlist.push(Item);
                    })
    
                    $.ajax({
                        url: '@Url.Action("Create", "Orders")', //
                        dataType: "json",
                        data: JSON.stringify({ itemlist : itemlist  }),
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (result) {
                            alert("success");
                        },
                        error: function (xhr) {
                            alert("error");
                        }
                    });
                });
            //});

    And you should delete [ValidateAntiForgeryToken] on controller,like:

           [HttpPost]
            //[ValidateAntiForgeryToken]
            public ActionResult Create(List<OrderItemsList> itemlist)

    How it works:(Now the data could be passed to controller)

    Best Regards.

    Yuki Tao

    Wednesday, November 14, 2018 10:24 AM
  • User1618447750 posted

    Hi <g class="gr_ gr_29 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="29" data-gr-id="29">mgebhard</g>, Yuki Tao

    • Many Thanks for your advice.
    • Really it was very useful for me. But, I'm still facing the same Error "<g class="gr_ gr_28 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="28" data-gr-id="28">itemlist</g> = null".
    • Let me show you my troubleshooting steps as the following:
      • step1: I clicked the "Create" button, successfully the click event was fired. The fields of the first row passed probably to "Item" variable.

    Step1

    •  Step2: the loop still running. The fields of the second row passed probably to "Item" variable.

    Step2

    •  Step3: the loop still running. The fields of the third row passed probably to "Item" variable.

    Step3

    •  Step4: the loop finished. The "Item" variable has 3 rows.

    Step4

    •  Step5: the AJAX function began.

    Step5

    • Step6: the surprise ...!!! the "<g class="gr_ gr_27 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="27" data-gr-id="27">itemlist</g>" var passed to the controller is "null", why?

    Step6

    Thanks for your support ...

    Monday, November 19, 2018 6:22 PM
  • User1520731567 posted

    Hi refa_karem,

    ???

    Can you upload your modified code?

    In my project,it works fine,like picture:

    Best Regards.

    Yuki Tao

    Tuesday, November 20, 2018 5:27 AM
  • User1618447750 posted

    Hi,

    Kindly, find the source code for my application. (Updated)

    https://drive.google.com/open?id=1Q2TxBYQfK3YY9wOlAwED-buY2hbWl9Cl

    Thanks ...

    Tuesday, November 20, 2018 3:11 PM
  • User1520731567 posted

    Hi refa_karem,

    I find you do not delete Initialization function and [ValidateAntiForgeryToken] Attributes in the View.

     //$(function () {
                $("#btnInsert").click(function () {
                    var itemlist = [];
    
                    //get cell values, instead of the header text.
                    $("#tbl tr:not(:first)").each(function () {
                        var tdlist = $(this).find("tr");
                        var Item = {
                            FilterType: $(tdlist[4]).html(),
                            FilterPartNumber: $(tdlist[5]).html(),
                            Quantity: $(tdlist[6]).html(),
                            OrderId: 1
                        };
                        itemlist.push(Item);
                    })
    
                    $.ajax({
                        url: '@Url.Action("Create", "Orders")', //
                        dataType: "json",
                        data: JSON.stringify({ itemlist: itemlist }),
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (result) {
                            alert("success");
                        },
                        error: function (xhr) {
                            alert("error");
                        }
                    });
                });
            //});
            [HttpPost]
            //[ValidateAntiForgeryToken]
            public ActionResult Create(List<OrderItemsList> itemlist)

    Best Regards.

    Yuki Tao

    Wednesday, November 21, 2018 10:03 AM
  • User1618447750 posted

    Hi Yuki Tao,

    I think you did not check my updated code. Please, find the following :

    Update code: https://drive.google.com/open?id=1Q2TxBYQfK3YY9wOlAwED-buY2hbWl9Cl

    The view: Create.cshtml

    @model FiltersReqSys.ViewModel.OrderOrderItemsListViewModel
    
    @{
        ViewBag.Title = "Create";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Create</h2>
    <h4>Order</h4>
    <h4>Here, you can add a new order.</h4>
    <hr />
    
    @using (Html.BeginForm())
    {
        @*@Html.AntiForgeryToken()*@
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    
        <div class="container">
            <div class="form-horizontal">
                <div class="panel-body">
                    <!-- FIRST COLUMN -->
                    <div class="col-sm-6">
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.OrderDate, htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.TextBoxFor(model => model.Order.OrderDate, "{0:dd/MM/yyyy}", new { @class = "form-control", @id = "OrderDateId", @Value = System.DateTime.Now.ToShortDateString() })
                                @Html.ValidationMessageFor(model => model.Order.OrderDate, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.RegionId, "Region", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("RegionId", null, htmlAttributes: new { @class = "form-control", @id = "RegionIdId" })
                                @Html.ValidationMessageFor(model => model.Order.RegionId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.DistrictId, "District", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("DistrictId", null, htmlAttributes: new { @class = "form-control", @id = "DistrictIdId" })
                                @Html.ValidationMessageFor(model => model.Order.DistrictId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.SupplierId, "Supplier", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("SupplierId", null, htmlAttributes: new { @class = "form-control", @id = "SupplierIdId" })
                                @Html.ValidationMessageFor(model => model.Order.SupplierId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                    </div>
    
                    <!-- SECOND COLUMN -->
                    <div class="col-sm-6">
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.FilterTypeId, "Filter Type", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("FilterTypeId", null, htmlAttributes: new { @class = "form-control", @id = "FilterTypeIdId" })
                                @Html.ValidationMessageFor(model => model.Order.FilterTypeId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.FilterListId, "Filter Part Number", htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.DropDownList("FilterListId", null, htmlAttributes: new { @class = "form-control", @id = "FilterListIdId" })
                                @Html.ValidationMessageFor(model => model.Order.FilterListId, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.FilterQuan, htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.EditorFor(model => model.Order.FilterQuan, new { htmlAttributes = new { @class = "form-control", @id = "FilterQuanId" } })
                                @Html.ValidationMessageFor(model => model.Order.FilterQuan, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
    
    
                        <div class="form-group">
                            @Html.LabelFor(model => model.Order.Note, htmlAttributes: new { @class = "col-sm-4 control-label" })
                            <div class="col-sm-8">
                                @Html.TextBoxFor(model => model.Order.Note, new { @class = "form-control", @id = "NoteId", @Value = "No Notes" })
                                @Html.ValidationMessageFor(model => model.Order.Note, "", new { @class = "text-danger" })
                            </div>
                        </div>
    
                    </div>
    
                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="button" value="Add New Row" class="btn btn-success" onclick="AddNew()" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    
    
        <table id="tbl" class="table table-hover">
            <thead>
                <tr>
                    <th>SN</th>
                    <th>Order Date</th>
                    <th>Region</th>
                    <th>District</th>
                    <th>FilterType</th>
                    <th>FilterPartNumber</th>
                    <th>Quantity</th>
                    <th>Supplier</th>
                    <th>Note</th>
                    <th>Action</th>
                </tr>
            </thead>
        </table>
    
        <div class="form-horizontal">
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-primary" id="btnInsert" />
                    @Html.ActionLink("Cancel or back to list", "Index", null, new { @class = "btn btn-default" })
                </div>
            </div>
        </div>
    
    }
    
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/JqueryDataTables")
    
        <script src="~/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
        @*<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>*@
    
        <script>
            // Set the row number of the table
            function RowNum($t) {
                var c = 0;
                $t.find("tr").each(function (ind, el) {
                    $(el).find("td:eq(0)").html(c++);
    
                });
            }
    
            // Remove the row of the table
            $(document).ready(function () {
                $("#tbl td input.rdelete").live("click", function () {
                    var srow = $(this).parent().parent();
                    srow.remove();
                    RowNum($("#tbl"));
                });
            });
    
            // Add new row to the table
            function AddNew() {
    
                var SN = SN;
                var OrderDate = $("#OrderDateId").val();
                var Region = $("#RegionIdId option:selected").text();
                var District = $("#DistrictIdId option:selected").text();
                var FilterType = $("#FilterTypeIdId option:selected").text();
                var FilterList = $("#FilterListIdId option:selected").text();
                var FilterQuan = $("#FilterQuanId").val();
                var Supplier = $("#SupplierIdId option:selected").text();
                var Note = $("#NoteId").val();
                var BtnDelete = "<input type=\"button\" value = \"Delete\" class=\"rdelete\"/>"
                var markup = "<tr><td>" + "</td><td>" + OrderDate + "</td><td>" + Region + "</td><td>" + District + "</td><td>" + FilterType + "</td><td>" + FilterList + "</td><td>" + FilterQuan + "</td><td>" + Supplier + "</td><td>" + Note + "</td><td>" + BtnDelete + "</td></tr>";
                $("#tbl tr:last").after(markup);
                RowNum($("#tbl"));
    
            }
    
            //Get all records from the table
    
                $("#btnInsert").click(function () {
                    var itemlist = [];
    
                    //get cell values, instead of the header text.
                    $("#tbl tr:not(:first)").each(function () {
                        //var tdlist = $(this).find("tr");
                        var Item = {
                            //FilterType: $(tdlist[4]).html(),
                            //FilterPartNumber: $(tdlist[5]).html(),
                            //Quantity: $(tdlist[6]).html(),
                            //OrderId: 1
                            FilterType: $(this).find(':nth-child(5)').text(), //fields same with OrderItemsList model
                            FilterPN: $(this).find(':nth-child(6)').text(),
                            FilterQuan: $(this).find(':nth-child(7)').text(),
                            OrderId: 1
                        };
    
    
                        itemlist.push(Item);
                    })
    
                    $.ajax({
                        url: '@Url.Action("Create", "Orders")', //
                        dataType: "json",
                        data: JSON.stringify({ itemlist : itemlist  }),
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (result) {
                            alert("success");
                        },
                        error: function (xhr) {
                            alert("error");
                        }
                    });
                });
    
        </script>
    }
    
    

    Also in the controller: OrdersController.cs

     [HttpPost]
            public ActionResult Create(List<OrderItemsList> itemlist)
            {
    
    
                //Oils = new List<OrderItemsList> {
                //    new OrderItemsList { FilterType = "Air Filter", FilterPN = "Refa1515", FilterQuan = 20, OrderId = 1 },
                //    new OrderItemsList { FilterType = "Air Filter", FilterPN = "Refa1616", FilterQuan = 16, OrderId = 1 },
                //    new OrderItemsList { FilterType = "Air Filter", FilterPN = "Refa1717", FilterQuan = 52, OrderId = 1 },
                //    new OrderItemsList { FilterType = "Air Filter", FilterPN = "Refa1818", FilterQuan = 60, OrderId = 1 }
                //};
    
                if (ModelState.IsValid)
                {
                    //var OrderItemList = new OrderItemsList();
    
    
                    foreach (var i in itemlist)
                    {
                        db.OrderItemsLists.Add(i);
                    }
    
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                return View(itemlist);
            }

    Wednesday, November 21, 2018 3:44 PM
  • User1520731567 posted

    Hi refa_karem,

    I find this part of code in my demo is removed the Initialization function,this may affect the code:

           // Remove the row of the table
            //$(document).ready(function () {
                $("#tbl td input.rdelete").delegate("click", function () {
                    var srow = $(this).parent().parent();
                    srow.remove();
                    RowNum($("#tbl"));
                });
            //});

    Best Regards.

    Yuki Tao

    Thursday, November 22, 2018 2:30 AM
  • User1618447750 posted

    Hi Yuki Tao,

    I removed the Initialization function. But still <g class="gr_ gr_98 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="98" data-gr-id="98">itemlist</g> = null.

    Regards,

    Thursday, November 22, 2018 3:21 PM