locked
how to pass the obejct array from the javacript function into the controller RRS feed

  • Question

  • User-1355965324 posted

    Hi

    How can I pass the object array from javascript function into the controller Please help

     function LockbreakDown() {
            debugger;
              
            report = table.rows({ selected: true }).data();
            
            $.ajax({
                type: "POST",
                url: "/Employee/CloseDepots",
                data: report,
                dataType: "json",
                success: function (data) {
                },
                failure: function (response) {
                    console.log(response.responseText);
                },
                error: function (response) {
                    console.log(response.responseText);
                }
            });
    
            
        }
    
     [HttpPost]
            public IActionResult CloseDepots(bring the value from report variable from 
                javacript function)
            {
                if (HttpContext.Session.GetInt32("UserID") != null)
                {
                    return View();
                }
                else
                {
                    return RedirectToAction("SessionExpiry", "Employee");
                }
    
    
            }

    Friday, November 15, 2019 4:53 PM

Answers

  • User-474980206 posted

    first pass as json:

            report = table.rows({ selected: true }).data();
            
            $.ajax({
                type: "POST",
                url: "/Employee/CloseDepots",
                data: JSON.serialize(report),
                contentType="application/json",
                dataType: "json",
                success: function (data) {
                },
                failure: function (response) {
                    console.log(response.responseText);
                },
                error: function (response) {
                    console.log(response.responseText);
                }
            });
    

    as you did not supply the json format, you will need to build a match class in C#. but make a class that matches the data format, then its just:

     public IActionResult CloseDepots(List<MyData> model)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 15, 2019 9:52 PM

All replies

  • User475983607 posted

    Pretty simple.  Define the object array in the action signature.  The forum members can only see the code that you share on the forum we have no idea how the data is formatted.  You are the only one that know the shape of the data.

    [HttpPost]
    public IActionResult CloseDepots(List<UnknownModel> input)
    {
    	if (HttpContext.Session.GetInt32("UserID") != null)
    	{
    		return View();
    	}
    	else
    	{
    		return RedirectToAction("SessionExpiry", "Employee");
    	}
    }

    Friday, November 15, 2019 5:55 PM
  • User-474980206 posted

    first pass as json:

            report = table.rows({ selected: true }).data();
            
            $.ajax({
                type: "POST",
                url: "/Employee/CloseDepots",
                data: JSON.serialize(report),
                contentType="application/json",
                dataType: "json",
                success: function (data) {
                },
                failure: function (response) {
                    console.log(response.responseText);
                },
                error: function (response) {
                    console.log(response.responseText);
                }
            });
    

    as you did not supply the json format, you will need to build a match class in C#. but make a class that matches the data format, then its just:

     public IActionResult CloseDepots(List<MyData> model)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 15, 2019 9:52 PM
  • User-1355965324 posted

    It is not working . the object report = table.rows({ selected: true }).data(); is giving some additional column as given in the link It provides the new column _proto_. So it is not parsing with model.

    https://drive.google.com/open?id=1DXDykhKL_DGLEZddrdf_PPF-__2M3xNe

    But my DepotModel only  have the column Address1, Address2, Adress3 , City, County , DepartmentID,DepotNo ....... Employee.

    Is there anyway can I pass the values from the column DepotNo from the obejct  report = table.rows({ selected: true }).data();  into the controller as list string. When  you clicck the link you can see how the value is coming into the obect report =  table.rows({ selected: true }).data()

     public IActionResult CloseDepots(list<string> DepotNo)

    Saturday, November 16, 2019 9:07 AM
  • User-474980206 posted

    If the data is not in the format the server wants, then use the array map function to change it to the format the server wants.

    Note: javascript uses prototype inheritance, and the debugger displays properties based on the inheritance tree. While json serializers follows the prototype chain, they look at the property type to decide if to include the property, so you don’t get functions, or read only properties like .length.

    Sunday, November 17, 2019 7:28 PM
  • User665608656 posted

    Hi polachan,

    Based on your current description and the code provided in the previous thread, do you want to pass the value of  'DepotNo' of all checked data to the controller as a list by clicking the button?

    If so , you can refer to the full code:

    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
        <link href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
    
        <script>
            var table;
            var selectvalue = []; // to receive all checked data of DepotNo values
            $(document).ready(function () {
                GetDepotList();
            });
            function LockbreakDown() {
                $.ajax({
                    type: "POST",
                    url: "/Employee/CloseDepots",
                    data: { 'DepotNo': selectvalue },
                    dataType: "json",
                    success: function (data) {
                    },
                    failure: function (response) {
                        console.log(response.responseText);
                    },
                    error: function (response) {
                        console.log(response.responseText);
                    }
                });
            }
            function GetDepotList() {
                var url = "https://api.myjson.com/bins/1us28";
                table = $('#DepotTable').DataTable({
                    "processing": true,
                    "ajax": {
                        "url": url,
                    },
                    'columnDefs': [
                        {
                            'targets': 0,
                            'checkboxes': { 'selectRow': true },
                            'searchable': false,
                            'orderable': false,
                            'className': 'dt-body-center',
                            'render': function (data, type, full, meta) {
                                return '<input type="checkbox" name="id[]" value="' + $('<div/>').text(data).html() + '">';
                            }
                        }],
                    order: [1, 'asc'],
                    scrollY: "400px",
                    scrollX: true,
                    paging: false,
                    createdRow: function (row, data, dataIndex) {
                        $(row).children('td').attr('style', 'text-align: center;vertical-align: middle;');
                    }
                });
                 
    // select all action $('#example-select-all').on('click', function () { var rows = table.rows({ 'search': 'applied' }).nodes(); $('input[type="checkbox"]', rows).prop('checked', this.checked); selectvalue = []; if (this.checked) { $('input[type="checkbox"]:checked:not(:first)').each(function () { selectvalue.push(table.row($(this).closest('tr')).data()[1]); }); } }); $('#example tbody').on('change', 'input[type="checkbox"]', function () { if (!this.checked) { var el = $('#example-select-all').get(0); if (el && el.checked && ('indeterminate' in el)) { el.indeterminate = true; } } }); //click checkbox event $('#DepotTable tbody').on('click', 'input[type="checkbox"]', function () { selectvalue = []; if (!this.checked) { $('#example-select-all').prop("checked", false); } else { if ($('input[type="checkbox"]:checked').length == $('#DepotTable tbody tr').length) { $('#example-select-all').prop("checked", true); } } if ($('#example-select-all').prop("checked")) { $('input[type="checkbox"]:checked:not(:first)').each(function () { selectvalue.push(table.row($(this).closest('tr')).data()[1]); }); } else { $('input[type="checkbox"]:checked').each(function () { selectvalue.push(table.row($(this).closest('tr')).data()[1]); }); } }); } </script> </head> <body> <form> <div class="col-md-1"> <button type="button" name="submitButton" value="Open" class="btn btn-primary form-control" onclick="LockbreakDown()"> Close Depots </button> </div> <div class="col-md-12 att-area"> <div class="table-responsive"> <table id="DepotTable" class="table table-bordered table-striped" style="width: 100%"> <thead> <tr> <th> <input type="checkbox" name="select_all" value="1" id="example-select-all" class="checkbox" /> </th> <th>Depot</th> <th>Depot Name</th> </tr> </thead> <tbody> <tr> <td></td> <td>DepotNo</td> <td>DepotName</td> </tr> </tbody> </table> </div> </div> </form> </body> </html>
     [HttpPost]
            public ActionResult CloseDepots(List<string> DepotNo)
            {
    // do something you want return View(); }

    Here is the result :

    Best Regards,

    YongQing.

    Monday, November 18, 2019 8:17 AM
  • User-857013053 posted
    Try this code :
    var
    operationCollection = []; var test1 = { name: "Bill", age: "55", address: "testing" }; operationCollection.push(test1); var test2 = { name: "Ben", age: "55", address: "testing" }; operationCollection.push(test2); var test3 = { name: "Flo", age: "55", address: "testing" }; operationCollection.push(test3); dataToPost = JSON.stringify({ methodParam: operationCollection }); $.ajax({ type: "POST", url: "/Home/AddPerson", contentType: "application/json; charset=utf-8", dataType: 'JSON', data: dataToPost, traditional: true });
    Friday, November 22, 2019 4:21 AM