How can pass from Datatable Data To Controller IActionResult

jewel 1,186 Reputation points
2024-04-16T06:59:10.3266667+00:00
I want to insert some data from my datatable into another table. The checked data in my datatable is the result of the controller's action through I ajax
I want to send array as parameter.
Thanks in advance for your help.
var table = $("#example").DataTable({
    "data": data,
    "columns": [
        {
            "orderable": false,
            "data": null,
            'render': function (data, type, full, meta) {
                return '<input type="checkbox" class="checkbox_check">';
            }
        },
        { "data": "orderNumber" },
        { "data": "totalvalue" },
    ],
    "order": [[0, 'desc']]
});

  function addata() {
     let number = []
     let value = []
 
     var objdate =
     {
         '_value': value,
         '_number': number
     };
     $.ajax({
         type: 'post',
         url: '/Home/adddata',
         data: objdate,
         success: function () {
             alert("Success")
         },
         Error: function () {
             alert("Error")
         }
     })
 }

public IActionResult adddata(int[] _number, decimal[] _value)

{

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

  {

      var pro = new tbl_order();

      pro.orderNumber = _number[i];

      pro.value = _value[i];

      _context.tbl_Orders.Add(pro);

      _context.SaveChanges();

  }

  return RedirectToAction("index");

}Screenshot (13)

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-04-16T13:01:12.99+00:00

    Hi @jewel,

    According to your description, you could use jquery selector to select the checkbox and then use push to push it to the backend.

    More details, you could refer to below test codes:

    Controller:

           public class Order
           {
               public int OrderNumber { get; set; }
               public decimal TotalValue { get; set; }
           }
           public IActionResult Index()
           {
               // Here you can fetch data from your database or any other source
               var orders = new List<Order>
           {
               new Order { OrderNumber = 1, TotalValue = 100 },
               new Order { OrderNumber = 2, TotalValue = 200 },
               new Order { OrderNumber = 3, TotalValue = 300 }
           };
               return View(orders);
           }
           [HttpPost]
           public IActionResult AddData(int[] _number, decimal[] _value)
           {
               // Handle insertion of data into the database
               // For simplicity, let's just return success
               return Ok();
           }
    

    View:

    <table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th></th>
                <th>Order Number</th>
                <th>Total Value</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var order in Model)
            {
                <tr>
                    <td><input type="checkbox" class="checkbox_check"></td>
                    <td>@order.OrderNumber</td>
                    <td>@order.TotalValue</td>
                </tr>
            }
        </tbody>
    </table>
    <button id="btnAddData">Add Data</button>
    @section Scripts {
        <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>
            $(document).ready(function () {
                var table = $('#example').DataTable();
                $('#btnAddData').on('click', function () {
                    addData();
                });
                function addData() {
                    var numbers = [];
                    var values = [];
                    $('.checkbox_check:checked').each(function () {
                        var rowData = table.row($(this).closest('tr')).data();
                        numbers.push(rowData[1]); // Assuming 'orderNumber' is in the second column (index 1)
                        values.push(rowData[2]); // Assuming 'totalValue' is in the third column (index 2)
                    });
                    var objData = {
                        _number: numbers,
                        _value: values
                    };
                    console.log(objData);
                    $.ajax({
                        type: 'POST',
                        url: '/Home/AddData',
                        data: objData,
                        traditional: true,
                        success: function () {
                            alert("Success");
                        },
                        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.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.