Add rows into datatable and insert multiple row into database

Analyst_SQL 3,551 Reputation points
2023-03-20T07:40:18.3+00:00

I am calling data on text field (Search_Prdno) event change to populate dropdown list and text field ,

now i want to insert multilpe rows into html table using json and insert into database from text field and dropdownlist

View

<div class="row">
        <div style="display: inline-block;">
            <div>
                @Html.LabelFor(model => model.Prdno, "Barcode", htmlAttributes: new { @class = "control-label col-md-4" })

                @Html.EditorFor(model => model.Prdno, new { htmlAttributes = new { @class = "form-control col-md-10", @id = "Search_Prdno" } })
                @Html.ValidationMessageFor(model => model.Prdno, "", new { @class = "text-danger" })
            </div>
        </div>

        <div style="display: inline-block;">
            <div>
                @Html.LabelFor(model => model.Codeitem, "Select Item", htmlAttributes: new { @class = "control-label col-md-3" })

                @Html.DropDownList("codeitemId", (SelectList)ViewBag.Codeitem, "Select", htmlAttributes: new { @class = "form-control", @id = "select2-3" })

                @Html.ValidationMessageFor(model => model.Codeitem, "", new { @class = "text-danger" })
            </div>
        </div>
        <div style="display: inline-block;">
            <div>
                @Html.LabelFor(model => model.Bale_QTY, "Bale_QTY", htmlAttributes: new { @class = "control-label col-md-4" })

                @Html.EditorFor(model => model.Bale_QTY, new { htmlAttributes = new { @class = "form-control col-md-10", @id = "Bale_Qty", @Value = "1" } })
                @Html.ValidationMessageFor(model => model.Bale_QTY, "", new { @class = "text-danger" })
            </div>
        </div>
        <div style="display: inline-block;">
            <div>
                @Html.LabelFor(model => model.Prdno, "BarCode", htmlAttributes: new { @class = "control-label col-md-4" })

                @Html.EditorFor(model => model.Prdno, new { htmlAttributes = new { @class = "form-control col-md-10", @id = "Barcode_Bale" } })
                @Html.ValidationMessageFor(model => model.Prdno, "", new { @class = "text-danger" })
            </div>
        </div>
        
        <div style="display: inline-block;">

            @Html.LabelFor(model => model.OrderNo, "OrderNo", htmlAttributes: new { @class = "control-label col-md-2", @id = "P_OrderNo" })
            @Html.HiddenFor(Model => Model.OrderNo)

        </div><div style="display: inline-block;">

            @Html.LabelFor(model => model.weight, "Weight", htmlAttributes: new { @class = "control-label col-md-2", @id = "I_Weigth" })
            @Html.HiddenFor(Model => Model.weight)

        </div>
    </div>




 function GetBarcodeSB(prdno) {

            $.ajax({
                async: true,
                type: 'GET',
                dataType: 'JSON',
                contentType: 'application/json; charset=utf-8',
                url: '/OrderPack/GetBarcodeSB',
                data: { prdno: prdno },
                success: function (data) {
                    $('#select2-3').empty();
                    $(data).each(function (index, item) {
                        $('#select2-3').append($('<option/>', { value: item.Value, text: item.Text }))
                            ;

                    })
                },
                error: function () {
                    alert("There is some problem to get.");
                    $("#P_Prdno").empty();
                    $("#P_OrderNo").empty();
                    $("#I_Weigth").empty();
                }
            });
        }


        function GetBarcodeweight(prdno) {

            $.ajax({
                async: true,
                type: 'GET',
                dataType: 'JSON',
                url: '/OrderPack/GetBarcodeweight',
                data: { prdno: prdno },
                success: function (data) {
                    console.log(data);
                    //populate the didden field
                    $("#Prdno").val(data.Prdno);
                    //populate the label
                    $("#Barcode_Bale").val(data.Prdno);

                    //populate the didden field
                    $("#OrderNo").val(data.OrderNo);
                    //populate the Orderno
                    $("#P_OrderNo").text(data.OrderNo);

                    //populate the didden field
                    $("#weight").val(data.weight);
                    //populate the label
                    $("#I_Weigth").text(data.weight);


                    //console.log($("#select2-1").val());
                    var orderNo1 = $('#P_OrderNo').html();
                    var orderNo2 = $('#Orderno-label-5').html();
                    if (orderNo1 == orderNo2) {
                        alert('same order');
                    }
                    else {
                        alert('Not same order');

                    }

                },
                //error: function () {
                //    //alert("There is some problem to get.");

                //}
            });
        }

    </script>

[HttpGet]
        public JsonResult GetBarcodeSB(int prdno)
        {
            int? Codeitem = DB.Probales.First(a => a.Prdno == prdno).Codeitem;
            var STATUS_LIST = (from s in DB.ItemMasterFiles
                               where s.CodeItem == Codeitem
                               select 
                                   new SelectListItem()
                               {
                                   Text = s.Descriptionitem,
                                   Value = s.CodeItem.ToString(),
                                   
                               })  .   ToList();
            return Json(STATUS_LIST, JsonRequestBehavior.AllowGet);

        }
        [HttpGet]
        public JsonResult GetBarcodeweight(int prdno)
        {
       


            var query = (from p in DB.Probales.Where(p => p.Prdno == prdno)
                        join i in DB.ItemMasterFiles on p.Codeitem equals i.CodeItem
           
                        select new { ItemMasterFile = i, Probale = p }  ).ToList();
      



            var user = query.FirstOrDefault();
            var model = new OrderVm()
            {

                Prdno = user.Probale.Prdno,
                OrderNo =user.Probale.OrderNo,
                weight=user.ItemMasterFile.weight     

            };
            return Json(model, JsonRequestBehavior.AllowGet);

        }
    }

}



Class

public class OrderVm
    {

        [Display(Name = "Select Order")]
        public int? OrderNo { get; set; }
        public int? SOrderNo { get; set; }
        public int? Codeitem { get; set; }
        [Display(Name = "Input Barcode")]
        public int? Prdno { get; set; }
        public int? orderqty { get; set; }
        public int? prdqty { get; set; }
        public int? packQty { get; set; }
        

        public int? Bale_QTY { get; set; }

              public int? weight { get; set; }

        public Probale smallbale { get; set; }
        public ItemMasterFile Itemasterfile { get; set; }
    }
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,288 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,307 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,876 Reputation points Microsoft Vendor
    2023-03-20T10:02:00.23+00:00

    Hi @akhter hussain,

    I added the functions you want on the basis of the demo I wrote for you before, you can refer to the following code:

    <div>
    
        <div class="row">
            <div style="display: inline-block;">
                <div>
                    @Html.LabelFor(model => model.Prdno, "Barcode", htmlAttributes: new { @class = "control-label col-md-4" })
    
                    @Html.EditorFor(model => model.Prdno, new { htmlAttributes = new { @class = "form-control col-md-10", @id = "Search_Prdno" } })
                    @Html.ValidationMessageFor(model => model.Prdno, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
            <thead>
                <tr>
                    <th style="width:150px">Name</th>
                    <th style="width:150px">Country</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>CodeItem</td>
                    <td>OrderNo</td>
                    <td><input type="button" value="Remove" onclick="Remove(this)" /></td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td>
    
                        <div style="display: inline-block;">
                            <div>
                                @Html.DropDownList("codeitemId", (SelectList)ViewBag.CodeItem, "Select", htmlAttributes: new { @class = "form-control", @id = "select2-3" })
    
                                @Html.ValidationMessageFor(model => model.CodeItem, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </td>
                    <td>
                        <div style="display: inline-block;">
                            <div>
                                @Html.LabelFor(model => model.OrderNo, "Order", htmlAttributes: new { @class = "control-label  col-md-2", @id = "quantity-label-2" })
                            </div>
                        </div>
                    </td>
                    <td><input type="button" id="btnAdd" value="Add" /></td>
                </tr>
            </tfoot>
        </table>
        <br />
        <input type="button" id="btnSave" value="Save All" />
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#Search_Prdno").change(function () {
                var prdno = $("#Search_Prdno").val();
                if (prdno != "") {
                    GetSections(prdno);
                    GetOrderno(prdno);
                }
                else {
                    $("#select2-3").empty();
                }
            });
        });
        function GetSections(prdno) {
            $.ajax({
                async: true,
                type: 'GET',
                dataType: 'JSON',
                contentType: 'application/json; charset=utf-8',
                url: '/Home/GetBarcodeSB',
                data: { prdno: prdno },
                success: function (data) {
                    $('#select2-3').empty();
                    $(data).each(function (index, item) {
                        $('#select2-3').append($('<option/>', { value: item.Value, text: item.Text }))
                    })
                },
                error: function () {
                    alert("There is some problem to get.");
                }
            });
        }
        function GetOrderno(prdno) {
    
            $.ajax({
                async: true,
                type: 'GET',
                dataType: 'JSON',
                url: '/Home/GetOrderno',
                data: { prdno: prdno },
                success: function (data) {
                    console.log(data);
                    //populate the didden field
    
                    //populate the label
                    $("#quantity-label-2").text(data);
                },
                error: function () {
                    alert("There is some problem to get.");
                }
            });
        }
    
        $("body").on("click", "#btnAdd", function () {
            //Reference the Name and Country TextBoxes.
            var txtCodeItem = $("#select2-3");
            var txtOrderNo = $("#quantity-label-2");
    
            //Get the reference of the Table's TBODY element.
            var tBody = $("#tblCustomers > TBODY")[0];
    
            //Add Row.
            var row = tBody.insertRow(-1);
    
    
            //Add Name cell.
            var cell = $(row.insertCell(-1));
            cell.html(txtCodeItem.find(":selected").text());
    
            //Add Country cell.
            cell = $(row.insertCell(-1));
            cell.html(txtOrderNo.text());
    
            //Add Button cell.
            cell = $(row.insertCell(-1));
            var btnRemove = $("<input />");
            btnRemove.attr("type", "button");
            btnRemove.attr("onclick", "Remove(this);");
            btnRemove.val("Remove");
            cell.append(btnRemove);
    
            //Clear the TextBoxes.
            txtCodeItem.find(":selected").text("");
            txtOrderNo.text("");
        });
    
        function Remove(button) {
            //Determine the reference of the Row using the Button.
            var row = $(button).closest("TR");
            var name = $("TD", row).eq(0).html();
            if (confirm("Do you want to delete: " + name)) {
                //Get the reference of the Table.
                var table = $("#tblCustomers")[0];
    
                //Delete the Table row using it's Index.
                table.deleteRow(row[0].rowIndex);
            }
        };
    
        $("body").on("click", "#btnSave", function () {
            //Loop through the Table rows and build a JSON array.
            var probales = new Array();
            $("#tblCustomers TBODY TR").each(function () {
                var row = $(this);
                var probale = {};
              
                probale.CodeItem = row.find("TD").eq(0).html();
                probale.OrderNo = row.find("TD").eq(1).html();
                probales.push(probale);
            });
    
            //Send the JSON array to Controller using AJAX.
            $.ajax({
                type: "POST",
                url: "/Home/Insert",
                data: JSON.stringify(probales),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    alert(r + " record(s) inserted.");
                }
            });
        });
    
    </script>
    
     public JsonResult Insert(List<OrderVm> orderVms)
            {
    
                using (TestEntities entities = new TestEntities())
                {
                    //Truncate Table to delete all old records.
                    entities.Database.ExecuteSqlCommand("TRUNCATE TABLE [OrderVms]");
    
                    //Check for NULL.
                    if (orderVms == null)
                    {
                        orderVms = new List<OrderVm>();
                    }
                    //Loop and insert records.
                    foreach (OrderVm orderVm in orderVms)
                    {
                        if (orderVm.OrderNo != 0)
                        {
                            entities.orderVms.Add(orderVm);
                        }
                    }
                    int insertedRecords = entities.SaveChanges();
                    return Json(insertedRecords);
                }
    
            }
    

    10

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful