how to pass data from child table to controller

jewel 801 Reputation points
2024-04-17T10:40:31.2233333+00:00

I got stuck in a tricky problem. I can't find the solution anywhere. Clicking on the row of my datatable opens the child table. Checkboxes are attached to both parent table and child table. Clicking the DataTable checkbox(name="Selectall" class="checkbox_check") makes the Child Table checkbox checked(name="Selectone" class="chk_isChecked"). Again clicking the child table text box(class="txt_qty") checks all the child table's checkboxes and datatable's checkboxes.

The problem is - when I click on the table (   $('#example tbody').on('click', 'td.details-control', function ()), the child table checked box is checked but when I hide the child table and reopen it, the child table's checked box becomes unchecked.

My requirement is - I want to pass all the data of child table to controller via ajax if checked box of datatable is checked. This is possible if you add CSS to the child table. Or whatever I want to get all the data including the data of my (class="txt_qty")text box.

<style>

td.details-control {

    background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center center;

    cursor: pointer;

}

tr.shown td.details-control {

    background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center center;

}

</style>

<button onclick="addata()" class="btn btn-primary btn-sm">Add </button>

<table id="example" class="display jo" style="width:100%">

<thead>

    <tr>

        <th></th>

        <th></th>

        <th>Order NO</th>

        <th>Total Value</th>

    </tr>

</thead>

</table>

@section Scripts {

@{

    await Html.RenderPartialAsync("_ValidationScriptsPartial");

}

<script type="text/javascript">

    function format(d) {

       

        var str = '';

        $.each(d.tbl_orderses, function (index, data) {

            str += '<tr>' +

                '<td>' + data.productID + '</td>' +

                '<td>' + data.oredrQty + '</td>' +

                '<td><input type="number" value="0" class="txt_qty" /></td>' +

                '<td><input type="checkbox"  name="Selectone" class="chk_isChecked" id="' + data.productID + '" /></td>' +

                '</tr>'

        });

        return '<table id=ntabl  style="padding-left:50px;">' +

            '<tr>' +

            '<td>ProductID</td><td>oredrQty</td><td>Return Qty</td><td>Check</td>' +

            '</tr>' +

            str +

            '</table>';

    }

    $(document).ready(function () {

        $.ajax({

            url: "/Home/Getrecord",

            type: "Get",

            contentType: "application/json; charset=utf-8",

            dataType: "json",

            success: function (data) {

                console.log("succsss" + data);

                var table = $("#example").DataTable({

                    "data": data,

                    "columns": [

                        {

                            "className": 'details-control',

                            "orderable": false,

                            "data": null,

                            "defaultContent": ''

                        },

                        {

                            "orderable": false,

                            "data": null,

                            'className': 'dt-body-center',

                            'render': function (data, type, full, meta) {

                                return '<input type="checkbox" name="Selectall" class="checkbox_check">';

                            }

                        },

                        { "data": "orderNumber" },

                        { "data": "totalvalue" },

                    ],

                    "order": [[0, 'desc']]

                });

                $('#example tbody').on('click', 'td.details-control', function () {

                    var tr = $(this).closest('tr');

                    var row = table.row(tr);

                    if (row.child.isShown()) {

                        row.child.hide();

                        tr.removeClass('shown');

                    }

                    else {

                        row.child(format(row.data(), row.node())).show();

                        tr.addClass('shown');

                    }

                });

                // When clicking on the column checkbox

              

                $('#example tbody').on('change', '.checkbox_check', function () {

         debugger

                    var isChecked = $(this).prop('checked');

                    var rowData = table.row($(this).closest('tr')).data();

                    // Check/uncheck all checkboxes in the child table

                    $(this).closest('tr').next('tr').find('.chk_isChecked').prop('checked', isChecked);

                });

           

                // When inputting a number in any text box

                $('#example tbody').on('input', '.txt_qty', function () {

                    var quantity = $(this).val();

                    var isChecked = quantity;

                    // Check all checkboxes in the child table

                    $(this).closest('table').find('.chk_isChecked').prop('checked', isChecked);

                    // Check the corresponding column checkbox

                    $(this).closest('table').closest('tr').prev('tr').find('.checkbox_check').prop('checked', isChecked);

                });

            },

            error: function (ex) {

                console.log(ex);

            }

        });

    })

function addata() {

    debugger

    var numbers = [];

    var values = [];

  var  table = $("#example").DataTable()

    $('.checkbox_check').each(function () {

        if ($(this).prop("checked")) {

            data = table.row($(this).parents('tr')).data();

            numbers.push(data.orderNumber);

            values.push(data.totalvalue);

            

        }

    });

    let valudata = []

    let txtqty = []

    $('input[name="Selectone"]:checked').each(function (i, data) { valudata.push(this.id) });

    $(".txt_qty").each(function (i, tm) {

        var txtvalue = $(tm).val();

        if (txtvalue.length > 0 && txtvalue != "0") {

            txtqty.push(txtvalue)

        }

    });

    var objdate =

    {

        'IDS': valudata,

        '_numbers': numbers,

        '_values': values,

        'qty': txtqty

    };

    $.ajax({

        type: 'post',

        url: '/Home/adddata',

        data: objdate,

        success: function () {

         

        },

        Error: function () {

            alert("Error")

        }

    })

}

</script>

public JsonResult Getrecord()

{

 var List = from a in _context.tbl_Orders

            group a by new { a.orderNumber } into g

            select new ordervm

            {

                orderNumber = g.Key.orderNumber,

                Totalvalue = g.Sum(x => x.value),

                tbl_orderses = g.Select(t => new tbl_order

                {

                    productID = t.productID,

                    oredrQty = t.oredrQty,

                    orderId = t.orderId,

                }).ToList()

            };

 return Json(List);

}

public IActionResult adddata(int[] IDS, int[] qty, string[] _numbers, decimal[] _values)

{

 for (int i = 0; i < IDS.Count(); i++)

 {

     

 }

 return RedirectToAction("index");

}

public class ordervm

{

    public int orderId { get; set; }

    public String orderNumber { get; set; }

    public int productID { get; set; }

    public int? oredrQty { get; set; }

    public Decimal? Totalvalue { get; set; }

    public List<tbl_order> tbl_orderses { get; set; }

}

public class tbl_order

{

[Key]

public int orderId { get; set; }

public int CustomerID { get; set; }

public String orderNumber { get; set; }

public int productID { get; set; }  

public int? oredrQty { get; set; }

public Decimal? salerate { get; set; }

public Decimal? value { get; set; }



[NotMapped]

public string ProductName { get; set; }

}record

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,176 questions
{count} votes

Accepted answer
  1. Brando Zhang-MSFT 2,956 Reputation points Microsoft Vendor
    2024-04-18T09:38:06.18+00:00

    Hi @jewel,

    Hope you are doing well.

    The reason why your input selector will not post all the data is your details button will use tr.child.hide this will remove generated nested table instead of just hiding it. So to solve this issue, I modify the jquery codes to firstly load all the nested table and then add them a css property display none to hide them.

    When click the details button, it will modify the css instead of use hide to remove the new generated table.

    More details, you could refer to below view codes:

    <style>
        td.details-control {
            background: url(' https://datatables.net/examples/resources/details_open.png') no-repeat center center;
            cursor: pointer;
        }
    
        tr.shown td.details-control {
            background: url(' https://datatables.net/examples/resources/details_close.png') no-repeat center center;
        }
    </style>
    
    <button onclick="addata()" class="btn btn-primary btn-sm">Add </button>
    
    <table id="example" class="display jo" style="width:100%">
        <thead>
    
            <tr>
    
                <th></th>
    
                <th></th>
    
                <th>Order NO</th>
    
                <th>Total Value</th>
    
            </tr>
    
        </thead>
    
    </table>
    
    @section Scripts {
        @{
    
            await Html.RenderPartialAsync("_ValidationScriptsPartial");
    
        }
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
    
    <script type="text/javascript">
    
        function format(d) {
            var str = '';
            $.each(d.tbl_orderses, function (index, data) {
                str += '<tr>' +
                    '<td>' + data.productID + '</td>' +
                    '<td>' + data.oredrQty + '</td>' +
                    '<td><input type="number" value="0" class="txt_qty" /></td>' +
                    '<td><input type="checkbox"  name="Selectone" class="chk_isChecked" id="' + data.productID + '" /></td>' +
                    '</tr>'
            });
    
            return '<table id=ntabl  style="padding-left:50px;">' +
                '<tr>' +
                '<td>ProductID</td><td>oredrQty</td><td>Return Qty</td><td>Check</td>' +
                '</tr>' +
                str +
                '</table>';
        }
    
        $(document).ready(function () {
    
            $.ajax({
    
                url: "/Home/Getrecord",
    
                type: "Get",
    
                contentType: "application/json; charset=utf-8",
    
                dataType: "json",
    
                success: function (data) {
    
                    console.log("succsss" + data);
    
                    var table = $("#example").DataTable({
    
                        "data": data,
    
                        "columns": [
    
                            {
    
                                "className": 'details-control',
    
                                "orderable": false,
    
                                "data": null,
    
                                "defaultContent": ''
    
                            },
    
                            {
    
                                "orderable": false,
    
                                "data": null,
    
                                'className': 'dt-body-center',
    
                                'render': function (data, type, full, meta) {
    
                                    return '<input type="checkbox" name="Selectall" class="checkbox_check">';
    
                                }
    
                            },
    
                            { "data": "orderNumber" },
    
                            { "data": "totalvalue" },
    
                        ],
    
                            "order": [[0, 'desc']],
                            //here I add a class to each root tr
                            rowCallback: function (row, data) {
                                $(row).addClass('roottr');
                            }
    
                    });
    
                    // I firstly load all the child tr data and set its display to none
                        $('.roottr').each(function (index, tr) {
                            debugger;
                            var row = table.row(tr);
                            row.child(format(row.data(), row.node())).show();
                            $(row.child()).css("display", "none")
                         
    
                           
                    });
    
                    // when click the details button, I modify the css isntead of using the hide which will not remove all the nested data to keep the input selector data 
                    $('#example tbody').on('click', 'td.details-control', function () {
                      
                        var tr = $(this).closest('tr');
    
                        var row = table.row(tr);
    
                        if ($(row.child()).css('display') == 'none') {
    
                            tr.addClass('shown');
                                $(row.child()).css("display", "")
                        } else 
                        {
                            tr.removeClass('shown');
                            $(row.child()).css("display", "none")
                        }
    
                    });
    
                    // When clicking on the column checkbox
    
    
    
                    $('#example tbody').on('change', '.checkbox_check', function () {
    
                        debugger
    
                        var isChecked = $(this).prop('checked');
    
                        var rowData = table.row($(this).closest('tr')).data();
    
                        // Check/uncheck all checkboxes in the child table
    
                        $(this).closest('tr').next('tr').find('.chk_isChecked').prop('checked', isChecked);
    
                    });
    
    
    
                    // When inputting a number in any text box
    
                    $('#example tbody').on('input', '.txt_qty', function () {
    
                        var quantity = $(this).val();
    
                        var isChecked = quantity;
    
                        // Check all checkboxes in the child table
    
                        $(this).closest('table').find('.chk_isChecked').prop('checked', isChecked);
    
                        // Check the corresponding column checkbox
    
                        $(this).closest('table').closest('tr').prev('tr').find('.checkbox_check').prop('checked', isChecked);
    
                    });
    
                },
    
                error: function (ex) {
    
                    console.log(ex);
    
                }
    
            });
    
        })
    
        function addata() {
    
            debugger
    
            var numbers = [];
    
            var values = [];
    
            var table = $("#example").DataTable()
    
            $('.checkbox_check').each(function () {
    
                if ($(this).prop("checked")) {
    
                    data = table.row($(this).parents('tr')).data();
    
                    numbers.push(data.orderNumber);
    
                    values.push(data.totalvalue);
    
    
    
                }
    
            });
    
            let valudata = []
    
            let txtqty = []
    
            $('input[name="Selectone"]:checked').each(function (i, data) { valudata.push(this.id) });
    
            $(".txt_qty").each(function (i, tm) {
    
                var txtvalue = $(tm).val();
    
                if (txtvalue.length > 0 && txtvalue != "0") {
    
                    txtqty.push(txtvalue)
    
                }
    
            });
    
            var objdate =
    
            {
    
                'IDS': valudata,
    
                '_numbers': numbers,
    
                '_values': values,
    
                'qty': txtqty
    
            };
    
            $.ajax({
    
                type: 'post',
    
                url: '/Home/adddata',
    
                data: objdate,
    
                success: function () {
    
    
    
                },
    
                Error: function () {
    
                    alert("Error")
    
                }
    
            })
    
        }
        </script>
    }
    
    

    Result:

    User's image

    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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful