0
\$\begingroup\$

I have this list of results which I display with the jQuery Datatables plugin.

This is the Result class and list of results being returned in the JSON format:

public class Result
{
            public int articleid { get; set; }
            public string Name { get; set; }
            public string Position { get; set; }
            public string Office { get; set; }
            public string Extn { get; set; }
            public string Startdate { get; set; }
            public string Salary { get; set; }
}

        [WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public static string GetJsonEmps()
        {
            List<Result> lsts = new List<Result>();
            for (int i = 1; i <= 10; i++)
            {
                lsts.Add(new Result() { articleid = i, Name = "AA" + i, Position = "home" + i, Office = "aas" + i, Extn = "extn" + i, Startdate = "date" + i, Salary = "sal" + i });
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            string json = js.Serialize(new { data = lsts });
            if (!string.IsNullOrEmpty(json))
            {
                return json;
            }
            return "";
        }

Client-side code

The code loads the datatable and adds a checkbox, where on save button click, I collect checked IDs:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" />
<script src="Scripts/jquery-1.11.1.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js" type="text/javascript"></script>

$(document).ready(function () {    

            $("#btnSave").click(function (e) {              
                var table = $('#example').DataTable();
                e.preventDefault();
                $(".chkcls").each(function () {
                    if (this.checked) {                     
                        var $row = $(this).closest('tr');
                        // Get row data
                        var data = table.row($row).data();
                        // Get row ID
                        var rowId = data[0];
                        alert("row id is " + rowId);
                    }
                });
            });    

            createtable();    
        });

        var datatable;
        function createtable() {
            $.ajax({
                type: "GET",
                url: "Jquery-datatable.aspx/GetJsonEmps",
                data: "{}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) { drawtable(response); },
                error: function (xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }

            });
        }


        function drawtable(result) {
            var result = $.parseJSON(result.d);
            var arrayReturn = [];
            for (var i = 0, len = result.data.length; i < len; i++) {
                var res = result.data[i];
                arrayReturn.push([res.articleid, res.Name, res.Position, res.Office, res.Extn, res.Startdate, res.Salary]);
            }       

            drawTable(arrayReturn);          
        }



 function drawTable(arr) {
            var table = $('#example').DataTable({
                iDisplayLength: 5,
                responsive: true,
                processing: true,
                "aaData": arr,
                columns: [
            { title: "Select" },
            { title: "Name" },
            { title: "Position" },
            { title: "Office" },
            { title: "Extn" },
            { title: "Startdate" },
            { title: "Salary" }
           ],
                "aoColumnDefs": [{
                    "aTargets": [0],                        
                    "mRender": function (data, type, full) {                           
                        if (isarticlesubmittable(data)) {
                            return '<input type=\"checkbox\" class=\"chkcls\" disabled="disabled" checked value="' + data + '">';
                        } else {
                            return '<input type=\"checkbox\" class=\"chkcls\" value="' + data + '">';
                        }
                    }
                }]
            });
        }
        function isarticlesubmittable(status) {
            return status == 1 || status == 3;
        }

Output:

enter image description here

I would like to know if any improvements can be made.

\$\endgroup\$
1
\$\begingroup\$

A few thoughts on the client-side code :

Fixes

  • the save handler appears not to do any saving.
  • $.ajax() dataType option is dataType: "json", therefore the result is parsed JOSN, which is passed to drawtable(), which does var result = $.parseJSON(result.d) implying that the parsed JSON object delivered by $.ajax contains further JSON. The server-side code appears to indicate that a one-shot json-parse will suffice. I can see no evidence of a .d property.
  • $.ajax() option data: "{}" - seems wrong.

Tidies

  • createtable(), drawTable() drawtable() and isarticlesubmittable() appear to be in the global namespace and could be moved inside the $(document).ready(function () {...}) structure.
  • drawtable() and drawTable() - very confusing. Rename one or other or simply roll drawTable() into drawtable().
  • Is isarticlesubmittable() really necessary? It's one line and only called once.
  • var datatable is not used. If it was, then you should be able to avoid var table = $('#example').DataTable(); in the save handler.
  • In the save handler, select with $(".chkcls:checked") and avoid the test if (this.checked) {...}.
  • $.ajax() success option will simplify to success: drawtable,.
  • Use result.data.map(...) to compose arrayReturn.
  • Unecessary escape characters in 'mRender': function() {...}.
  • Avoid unnecessary assignments.

Doing the tidyies, not the fixes, I get :

$(document).ready(function () {
    var datatable;
    $("#btnSave").click(function (e) {
        e.preventDefault();
        if(datatable) {
            $(".chkcls:checked").each(function () {
                alert("row id is " + datatable.row($(this).closest('tr')).data()[0]);
            });
        }
    });
    $.ajax({
        'type': 'GET',
        'url': 'Jquery-datatable.aspx/GetJsonEmps',
        'data': '{}',
        'dataType': 'json',
        'contentType': 'application/json; charset=utf-8',
        'success': drawtable,
        'error': function (xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
    });
    function drawtable(result) {
        var result = $.parseJSON(result.d);
        datatable = $('#example').DataTable({
            'iDisplayLength': 5,
            'responsive': true,
            'processing': true,
            'aaData': result.data.map(function(res) {
                return [res.articleid, res.Name, res.Position, res.Office, res.Extn, res.Startdate, res.Salary];
            }),
            'columns': [
                { 'title': 'Select' },
                { 'title': 'Name' },
                { 'title': 'Position' },
                { 'title': 'Office' },
                { 'title': 'Extn' },
                { 'title': 'Startdate' },
                { 'title': 'Salary' }
            ],
            'aoColumnDefs': [{
                'aTargets': [0],
                'mRender': function (data, type, full) {
                    if (data == 1 || data == 3) {
                        return '<input type="checkbox" class="chkcls" disabled="disabled" checked value="' + data + '">';
                    } else {
                        return '<input type="checkbox" class="chkcls" value="' + data + '">';
                    }
                }
            }]
        });
    }
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy