Get jQuery DataTables Column value as comma separated in ASP.Net MVC

Last Reply 2 days ago By dharmendr

Posted 3 days ago

Hi Developers , 

i want to save all records one by one using jquery in mvc.

Records bind on a html div. 

In this tblDetails having 5 records one by one as gridview. Now i want to get database saved Id of the 5 records and need to store in a single variable. Should Insert the variable value to database.

For Example 

Binding Records to me (Jquery html table)

StudentId      Name   Age 

111               Paul1     26

112               Paul2     27

113               Paul3      28

114               Paul4      29

115               Paul5      30

My Expected Output in Jquery

studentId= "111,112,113,114,115" (Split by Comma) 

    $('#tblDetails').dataTable({
        "processing": true, // control the processing indicator.
        "serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
        "info": true,   // control table information display field
        "stateSave": false,  //restore table state on page reload,
        "lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]],    // use the first inner array as the page length values and the second inner array as the displayed options
        "pageLength": 100,
        "ajax": {
            "url": pathIndex("ReconReports") + '/GenericReport/GetData?viewdataName=PaymentPGReversal_Temp',
            "type": "POST",
            "contentType": "application/json",
            "dataType": "JSON",
            "data": function (d) {
                return JSON.stringify(d);
            },
            "dataSrc": function (json) {
                var jsonp = JSON.parse(json.ResponseContent);
                json.draw = jsonp.draw;
                json.recordsTotal = jsonp.recordsTotal;
                json.recordsFiltered = jsonp.recordsFiltered;
                json.data = jsonp.data;
                var return_data = json;
                return return_data.data;


            }
        },
        "columns": title,
        dom: 'Bfrtip',
        buttons: [
	      {
	          text: '<i class="fa fa-file-excel-o"> Excel</i>',
		  action: function (e, dt, node, config) {
		      ExportExcel();
		  }
	      },
              {
                  text: '<i class="fa fa-file-pdf-o"> PDF</i>',
                  action: function (e, dt, node, config) {
                      ExportPDF();
                  }
              },
        ],
        responsive: true,
        "fnDrawCallback": function (oSettings) {
        },
        "order": [[0, "asc"]],
        "error": function () {
            alert("DataTables warning: JSON data from server failed to load or be parsed. " +
            "This is most likely to be caused by a JSON formatting error.");
        }
    });
    $("body").on("click", "#btnSubmitAll", function () {
        var TableData;
        TableData = storeTblValues()
        var myJsonString = JSON.stringify(TableData);
        myJsonString = myJsonString.replace(/([.€])+/g, '');
        alert(myJsonString) 
    });
 
    function storeTblValues() {
        var TableData = new Array();
        $('#tblDetails tr').each(function (row, tr) {
            TableData[row] = {
                '': $(tr).find('td:eq(0)').text()
            }
        });
        TableData.shift(); // first row will be empty - so remove
        return TableData;
    }

Thanking you

Paul.S

Posted 2 days ago

Hi paulrajmca,

Using the below article i have binded the html table. You need to bind the way you are binding.

Using jQuery DataTables in ASP.Net MVC

Only i have changed the code to get the first cell values as comma separated value.

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult AjaxMethod()
    {
        NorthwindEntities entities = new NorthwindEntities();
        List<Customer> customers = (from customer in entities.Customers.Take(5)
                                    select customer).ToList();
        return Json(customers);
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div style="width: 500px">
        <table id="tblDetails" cellpadding="0" cellspacing="0" border="1" style="border-collapse:collapse">
            <thead>
                <tr>
                    <th>Customer Id</th>
                    <th>Name</th>
                    <th>City</th>
                    <th>Country</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
        <br />
        <input type="button" id="btnSubmitAll" name="name" value="Submit" />
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
    <link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    $("#tblDetails").DataTable({
                        bLengthChange: true,
                        lengthMenu: [[5, 10, -1], [5, 10, "All"]],
                        bFilter: true,
                        bSort: true,
                        bPaginate: true,
                        data: response,
                        columns: [{ 'data': 'CustomerID' },
                                  { 'data': 'ContactName' },
                                  { 'data': 'City' },
                                  { 'data': 'Country' }]
                    });
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (response) {
                    alert(response.d);
                }
            });
        });
        $("body").on("click", "#btnSubmitAll", function () {
            var TableData;
            TableData = storeTblValues()
            var myJsonString = TableData.join(",");
            alert(myJsonString)

        });
        function storeTblValues() {
            var TableData = new Array();
            $('#tblDetails tbody tr').each(function (row, tr) {
                TableData.push($(tr).find('td:eq(0)').html());
            });
            return TableData;
        }
    </script>
</body>
</html>

Screenshot