\$\begingroup\$
\$\endgroup\$
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:
I would like to know if any improvements can be made.
Quill
12k5 gold badges41 silver badges93 bronze badges
asked Jan 16, 2016 at 5:43
user59802user59802
1 Answer 1
\$\begingroup\$
\$\endgroup\$
A few thoughts on the client-side code :
Fixes
- the save handler appears not to do any saving.
$.ajax()
dataType option isdataType: "json"
, therefore the result is parsed JOSN, which is passed todrawtable()
, which doesvar 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()
optiondata: "{}"
- seems wrong.
Tidies
createtable()
,drawTable()
drawtable()
andisarticlesubmittable()
appear to be in the global namespace and could be moved inside the$(document).ready(function () {...})
structure.drawtable()
anddrawTable()
- very confusing. Rename one or other or simply rolldrawTable()
intodrawtable()
.- 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 avoidvar table = $('#example').DataTable();
in the save handler. - In the save handler, select with
$(".chkcls:checked")
and avoid the testif (this.checked) {...}
. $.ajax()
success option will simplify tosuccess: drawtable,
.- Use
result.data.map(...)
to composearrayReturn
. - 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 + '">';
}
}
}]
});
}
});
answered Jan 16, 2016 at 14:24
lang-cs