i have created a webservice in Asp.net which is returning the following
<string xmlns="http://tempuri.org/">[{"Id":13,"FirstName":"Mohsin","LastName":"Mustufa","Birthday":"12/11/1990","Phone":null,"Email":"abcd#yahoo.com","UserId":"11"}]
now i want to populate that data in Jquery Datatable
here is the HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Birthday</th>
<th>Phone</th>
<th>Email</th>
<th>UserId</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>FirstName</th>
<th>LastName</th>
<th>Birthday</th>
<th>Phone</th>
<th>Email</th>
<th>UserId</th>
</tr>
</tfoot>
</table>
Jquery
$.ajax({
type: 'POST',
url: 'ws.asmx/ContactsList',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(data.d);
$('#example').dataTable({
"aaData": data.d,
"aoColumns": [
{
"mDataProp": "Id"
}, {
"mDataProp": "FirstName"
}, {
"mDataProp": "LastName"
}, {
"mDataProp": "Birthday"
}, {
"mDataProp": "Phone"
}, {
"mDataProp": "Email"
}, {
"mDataProp": "UserId"
}
]
});
}});
here data.d is showing the following when console.log is called
[{"Id":13,"FirstName":"Mohsin","LastName":"Mustufa","Birthday":"12/11/1990","Phone":null,"Email":"abcd#yahoo.com","UserId":"11"}]
webservice
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string ContactsList()
{
var contacts = new List<ContactsModel>();
var conn = ConfigurationManager.ConnectionStrings["AccountsConnectionString"].ConnectionString;
using (var con = new SqlConnection(conn))
{
con.Open();
const string query = "SELECT [Id], [F_name], [L_name], [Phone], [Birthday], [Email], [User_id] FROM [Contacts]";
var cmd = new SqlCommand(query, con);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var model = new ContactsModel();
model.Id = Convert.ToInt32(reader["Id"].ToString());
model.FirstName = reader["F_name"].ToString();
model.LastName = reader["L_name"].ToString();
model.Birthday = reader["Birthday"].ToString();
model.Email = reader["Email"].ToString();
model.UserId = reader["User_id"].ToString();
contacts.Add(model);
}
}
return new JavaScriptSerializer().Serialize(contacts);
}
Error
Request Unknown parameter 'Id' for Row 0
Seems that data returned by the web service are interpreted as string. Try to use JSON.parse(data.d)
http://plnkr.co/edit/JGzCNT6Zg73xtFwAUuOx?p=preview
$(document).ready(function() {
var data = {
d : '[{"Id":13,"FirstName":"Mohsin","LastName":"Mustufa","Birthday":"12/11/1990","Phone":null,"Email":"abcd#yahoo.com","UserId":"11"}]'
};
$('#example').dataTable({
"aaData": JSON.parse(data.d),
"aoColumns": [
{
"mDataProp": "Id"
}, {
"mDataProp": "FirstName"
}, {
"mDataProp": "LastName"
}, {
"mDataProp": "Birthday"
}, {
"mDataProp": "Phone"
}, {
"mDataProp": "Email"
}, {
"mDataProp": "UserId"
}
]
});
} );
Related
I face the issue with jQuery Datatable server-side processing in ASP.NET Core 3.1. Server-side returns data as JSON but it is not displaying in Datatable.
Below is my controller side code
public IActionResult LoadData()
{
var dict = Request.Form.ToDictionary(x => x.Key, x => x.Value.ToString());
var draw = dict["draw"];
var start = dict["start"];
var length = dict["length"];
////Find Order Column
var sortColumn = "Company";
var sortColumnDir = "asc";
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
DataSet ddata = GenralClass.GetCRMTestData((Convert.ToInt32(draw)-1)*100, 100);//GetCRMData();
ddata.Tables[0].TableName = "data";
var data = ddata;
int recordsTotal = 34790;
var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
return Ok(JsonConvert.SerializeObject(jsonData));
}
Below is my view side code
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th style="white-space: nowrap;">Company</th>
<th style="white-space: nowrap;">Assignedto</th>
<th style="white-space: nowrap;">Provider</th>
</tr>
</thead>
</table>
Below is my Jquery Code.
$(document).ready(function () {
$('.dataTables-example').DataTable({
pageLength: 100,
processing: true,
serverSide: true,
ajax: {
url: '#Url.Action("LoadData", "SKU")',
type: 'POST',
dataType: "json",
columns: [
{ "data": "Company" },
{ "data": "Assignedto" },
{ "data": "Provider" },
]
}
});
});
I made some changes in startup.cs file in service configuration as below
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
services.AddControllers();
services.AddRazorPages();
services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("AppDb")));
}
No error display when page load just empty table. I verify from the chrome network that data is returning from the server-side as the data attached below. I don't know what is wrong why the data is not showing. The paging number showing correct but the data is not showing. Any help.
{
"draw":"1",
"recordsFiltered":34790,
"recordsTotal":34790,
"data":{
"data":[
{
"Company":"SHAN FOODS (PVT) LTD",
"Assignedto":"Stock-Transfer",
"Provider":"Stock-Transfer"
},
{
"Company":"SHAN FOODS (PVT) LTD",
"Assignedto":"Vermicelli (150gm)",
"Provider":"030180010017"
}
]
}
}
You can change your code as follows.
LoadData:
public IActionResult LoadData()
{
//...
var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data };
return new JsonResult(new {json = jsonData });
}
Jquery:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/SKU/LoadData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
});
});
function OnSuccess(response) {
$('.dataTables-example').DataTable(
{
data: response.json.data,
columns: [
{ "data": "company" },
{ "data": "assignedto" },
{ "data": "provider" },
],
});
};
Test result:
Change your json like below
{
"draw":"1",
"recordsFiltered":34790,
"recordsTotal":34790,
"data":[
{
"Company":"SHAN FOODS (PVT) LTD",
"Assignedto":"Stock-Transfer",
"Provider":"Stock-Transfer"
},
{
"Company":"SHAN FOODS (PVT) LTD",
"Assignedto":"Vermicelli (150gm)",
"Provider":"030180010017"
}
]
}
I have Programmed in MVC which works fine. but in a few chrome browser the columnd widths are different. This is correct Table
You can see the red underline and this is the wrong one.
as you can see the first three columns are wider than they should be.
this is the code
<div class="col-md-9" style="background-color:gainsboro">
<table cellpadding="0" cellspacing="0" border="0" class=" display stripe row-border order-column" id="example">
<thead>
<tr>
<th style="width:1%">fld_Id</th>
<th style="width:1%">ref_Id</th>
<th style="width:1%">Letter_Id</th>
<th style="width:1%">Flags</th>
<th style="width:1%">Status</th>
<th style="width:1%">كد</th>
<th style="width:1%">نوع</th>
<th style="width:29%">ارجاع دهنده</th>
<th style="width:30%">موضوع ارجاع</th>
<th style="width:30%">موضوع نامه</th>
<th style="width:1%">تاريخ دريافت</th>
<th style="width:1%"></th>
<th style="width:1%"></th>
<th style="width:1%"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
I am using MVC , Bootstrap v3.0.0, DataTable jquery. how can I find the problem to make them look the same in different borwsers?
Edit Section:
The Data inside of the Table will be populated by DataTable Jquery server Side. So I made the Client Side DataTable . The result was Ok and no difference in different Browser. when I use the Server Side DataTable the difference will be shown
This is the code that I use to populate the DataTable
<script type="text/javascript">
var BindDataTable = function (clicked_id) {
var table = $("#example").DataTable({
"destroy": true,
"bServerSide": true,
"sAjaxSource": "/Main/GetLetterList",
"fnServerData": function (sSource, aoData, fnCallback) {
aoData.push({ "name": "fld_id", "value": boldMenu });
$.ajax({
type: "Get",
data: aoData,
url: sSource,
dataType: "json",
success: fnCallback,
error: function (response) {
window.location.href = '/ACCLogin/Login/';
}
})
},
"fnDrawCallback": function () {
var UnBoldMenu = "#" + $("#unBoldMenu").val();
$("#ulTreeview").find(UnBoldMenu).css('font-weight', 'normal');
},
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
if (aData["Flags"] == "4") {
$('td', nRow).css('font-weight', 'bold');
}
if (aData["Status"] == "1") {
$('td', nRow).css('background-color', 'lightgreen');
}
},
"aoColumns": [
{ "mData": "fld_Id" },
{ "mData": "ref_Id" },
{ "mData": "Letter_Id" },
{ "mData": "Flags" },
{ "mData": "Status" },
{ "mData": "ProjectCode" },
{ "mData": "LetterType" },
{ "mData": "Referrer" },
{ "mData": "Ref_subject" },
{ "mData": "Letter_subject" },
{ "mData": "Date_Received" },
{
"mData": "ref_Id",
"render": function (ref_Id, aoData, type, full, meta) {
return '<li class="glyphicon glyphicon-eye-open"></li>'
}
}, {
"mData": "ref_Id",
"render": function (ref_Id, type, full, meta) {
return '<li class="glyphicon glyphicon-edit"></li>'
}
}
, {
"mData": "Letter_Id",
"render": function (Letter_Id, type, full, meta) {
return '<li class="glyphicon glyphicon-retweet"></li>'
}
}
]
})
.columns.adjust();
if (clicked_id!=-16)
table.columns([0, 1, 2, 3, 4]).visible(false);
else
table.columns([0, 1, 2, 3, 4,12]).visible(false);
}
var ViewLetter = function (refId) {
var url = "/Main/ViewLetter?Ref_Id=" + refId;
$('body').css('cursor', 'wait');
$("#myModalBodyDiv").load(url, function () {
$("#myModal").modal("show");
})
}
var ReferenceLetter = function (refId) {
var url = "/Main/ReferenceLetter?Ref_Id=" + refId;
$("#myModalBodyDivRefer").load(url, function () {
$("#myModalRefer").modal("show");
})
}
var ReferenceList = function (letterId) {
var url = "/Main/ReferenceList?Letter_Id=" + letterId;
$("#myModalBodyDivReferList").load(url, function () {
$("#myModalReferList").modal("show");
})
}
</script>
I call BindDataTable on document.ready
I set the width of each column from Jquery and remove it from . so the code is like this:
<div class="col-md-9" style="background-color:gainsboro">
<table cellpadding="0" cellspacing="0" border="0" class=" display stripe row-border order-column" id="example">
<thead>
<tr>
<th>fld_Id</th>
<th>ref_Id</th>
<th>Letter_Id</th>
<th>Flags</th>
<th>Status</th>
<th>كد</th>
<th>نوع</th>
<th>ارجاع دهنده</th>
<th>موضوع ارجاع</th>
<th>موضوع نامه</th>
<th>تاريخ دريافت</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
and set the width in jquery like this:
<script type="text/javascript">
var CategoryClick = function (clicked_id) {
var boldMenu = $("#boldMenu").val();
if (boldMenu != clicked_id)
$("#unBoldMenu").val(boldMenu);
$("#boldMenu").val(clicked_id);
var str = "#" + clicked_id;
$("#ulTreeview").find(str).css('font-weight', 'bold');
BindDataTable(clicked_id);
}
var BindDataTable = function (clicked_id) { //response
var boldMenu = $("#boldMenu").val();
if (#User.Identity.Name=="" || #User.Identity.Name==null)
window.location.href = '/ACCLogin/Login/';
var table = $("#example").DataTable({
"destroy": true,
"bServerSide": true,
"sAjaxSource": "/Main/GetLetterList",
"fnServerData": function (sSource, aoData, fnCallback) {
aoData.push({ "name": "fld_id", "value": boldMenu });
$.ajax({
type: "Get",
data: aoData,
url: sSource,
dataType: "json",
success: fnCallback,
error: function (response) {
window.location.href = '/ACCLogin/Login/';
}
})
},
"fnDrawCallback": function () {
var UnBoldMenu = "#" + $("#unBoldMenu").val();
$("#ulTreeview").find(UnBoldMenu).css('font-weight', 'normal');
},
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
if (aData["Flags"] == "4") {
$('td', nRow).css('font-weight', 'bold');
}
if (aData["Status"] == "1") {
$('td', nRow).css('background-color', 'lightgreen');
}
},
"aoColumns": [
{
"mData": "fld_Id",
"width": "1%"},
{
"mData": "ref_Id",
"width": "1%" },
{
"mData": "Letter_Id",
"width": "1%" },
{
"mData": "Flags",
"width": "1%" },
{
"mData": "Status",
"width": "1%" },
{
"mData": "ProjectCode",
"width": "1%" },
{
"mData": "LetterType",
"width": "1%" },
{
"mData": "Referrer",
"width": "29%" },
{
"mData": "Ref_subject",
"width": "30%" },
{
"mData": "Letter_subject",
"width": "30%" },
{
"mData": "Date_Received",
"width": "1%" },
{
"mData": "ref_Id",
"width": "1%",
"render": function (ref_Id, aoData, type, full, meta) {
return '<i class="glyphicon glyphicon-eye-open"></li>'
}
}, {
"mData": "ref_Id",
"width": "1%",
"render": function (ref_Id, type, full, meta) {
return '<i class="glyphicon glyphicon-edit"></li>'
}
}
, {
"mData": "Letter_Id",
"width": "1%",
"render": function (Letter_Id, type, full, meta) {
return '<i class="glyphicon glyphicon-retweet"></li>'
}
}
]
})
.columns.adjust();
if (clicked_id!=-16)
table.columns([0, 1, 2, 3, 4]).visible(false);
else
table.columns([0, 1, 2, 3, 4,12]).visible(false);
}
var ViewLetter = function (refId) {
var url = "/Main/ViewLetter?Ref_Id=" + refId;
$('body').css('cursor', 'wait');
$("#myModalBodyDiv").load(url, function () {
$("#myModal").modal("show");
})
}
var ReferenceLetter = function (refId) {
var url = "/Main/ReferenceLetter?Ref_Id=" + refId;
$("#myModalBodyDivRefer").load(url, function () {
$("#myModalRefer").modal("show");
})
}
var ReferenceList = function (letterId) {
var url = "/Main/ReferenceList?Letter_Id=" + letterId;
$("#myModalBodyDivReferList").load(url, function () {
$("#myModalReferList").modal("show");
})
}
and problem solved. all the borwsers shows the same Table columns widths.
Hi i am still learning MVC. I have a requirement where i have a page with dropdownlist with table name. When the user chooses the table name, a partial view will be called to display the data in DataTable.
Currently, i am having an issue when trying to display the DataTable. The post action, GetDPUserList() is not triggered thus the data is not showing.
Here is how i call my partial view:
$('#ddPatchingAction').change(function () {
ddPatchingActionValue = $('#ddPatchingAction option:selected').val();
if (ddPatchingActionValue) {
$.get("/PatchingBatch/DataTableBatch", function (data) {
$('#divPatching').html(data);
$('#batchTable').DataTable();
});
}
});
Here is the partial view:
<table id="batchTable" class="table-striped table-responsive">
<thead>
<tr>
<th>Username</th>
<th>Name</th>
<th>Email Address</th>
<th>Is Admin</th>
<th></th>
</tr>
</thead>
</table>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
#section scripts{
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
var popup, dataTable;
$(document).ready(function () {
dataTable = $("#batchTable").DataTable({
"ajax": {
"url": "/PatchingBatch/GetDPUserList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Username", "name":"Username" },
{ "data": "Name", "name": "Name" },
{ "data": "Email", "name": "Email" },
{ "data": "IsAdmin", "name": "IsAdmin" },
{
"data": "DPUserID", "render": function (data) {
return "<a class='btn btn-primary btn-sm' onclick=EditUserForm('#Url.Action("UpdateUser", "Account")/" + data +"')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left: 5px' onclick=Delete(" + data +")><i class='fa fa-trash'></i> Delete</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
},
],
"processing": "true",
"serverSide": "true",
"order": [0, "asc"]
});
});
function AddUserForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Add User Account",
height: 250,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
function EditUserForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Update User Account",
height: 410,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
$.validator.unobtrusive.parse(form);
if ($(form).valid()) {
$.ajax({
type: "POST",
url: form.action,
data: $(form).serialize(),
success: function (data) {
if (data.success) {
popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
});
}
return false;
}
function Delete(id) {
if (confirm("Are you sure you want to delete this data?")) {
$.ajax({
type: "POST",
url: '#Url.Action("DeleteUser", "Account")/' + id,
success: function (data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message, {
globalPosition: "top center",
className: "success"
})
}
}
}
)
}
}
</script>
}
Here is the controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using MVCWeb.Models;
using System.Linq.Dynamic;
namespace MVCWeb.Controllers
{
public class PatchingBatchController : Controller
{
// GET: PatchingBatch
public ActionResult DataTableBatch()
{
return PartialView();
}
[HttpPost]
public ActionResult GetDPUserList()
{
//server side parameter
int start = Convert.ToInt32(Request["start"]);
int length = Convert.ToInt32(Request["length"]);
string searchValue = Request["search[value]"];
string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][name]"];
string sortDirection = Request["order[0][dir]"];
List<DP_User> userList = new List<DP_User>();
using (DBModel db = new DBModel())
{
userList = db.DP_User.ToList<DP_User>();
userList = userList.ToList<DP_User>();
int totalrows = userList.Count();
//search
if (!string.IsNullOrEmpty(searchValue))
{
userList = userList.Where(x => (x.Username != null && x.Username.ToString().ToLower().Contains(searchValue)) ||
(x.Name != null && x.Name.ToString().ToLower().Contains(searchValue)) ||
(x.Email != null && x.Email.ToString().ToLower().Contains(searchValue))).ToList<DP_User>();
}
int totalrowsafterfilter = userList.Count();
//sorting
if (!string.IsNullOrEmpty(sortColumnName) && !string.IsNullOrEmpty(sortDirection))
{
userList = userList.OrderBy(sortColumnName + " " + sortDirection).ToList<DP_User>();
}
//paging
userList = userList.Skip(start).Take(length).ToList<DP_User>();
return Json(new { data = userList, draw = Request["draw"], recordsTotal = totalrows, recordsFiltered = totalrowsafterfilter },
JsonRequestBehavior.AllowGet);
}
}
}
}
I have checked in chrome console, but there is no error. So i am not sure what is the problem. Is there something wrong with my code? Please help. Thank you.
i am trying to bind json to table using datatable
here is my code Html
<table class="table table-bordered table-striped" id="dataTables-1">
<thead>
<tr>
<th>Customer Site Id</th>
<th>Customer Product name</th>
<th>Start Date Time</th>
<th>Stop Date Time</th>
<th>Upload</th>
<th>Download</th>
</tr>
</thead>
<tbody></tbody>
</table>
and here is script of datatable
<script type="text/javascript">
$("#btnFilter").click(function () {
//var tab = $("#Tab").val().length;
//var fromDate = $("#FromModel").val();
//var toDate = $("#ToDate").val();
CreateTableUsage();
});
function CreateTableUsage() {
$('#dataTables-1').DataTable({
searching: false,
'bAutoWidth': false,
sAjaxSource: '#Url.Action("Filter") + ?tab=' + encodeURI($('#Tab').val()) + encodeURI($('#FromModel').val()) + encodeURI($('#ToDate').val()),
aoColumns: [
{ "sName": "SiteRefId", "bSortable": false },
{ "sName": "CustomerServiceRefId", "bSortable": false },
{ "sName": "StartTimeUtc", "bSortable": false },
{ "sName": "StopTimeUtc", "bSortable": false },
{ "sName": "CallingStationId", "bSortable": false },
{ "sName": "IpAddress", "bSortable": false }]
});
}
</script>
here is code BackEnd
public ActionResult Filter(string tab, string FromDate, string ToDate)
{
return Json(new { aaData = lUsage.Select( x => new object[] { x.SiteRefId, x.CustomerServiceRefId, x.StartTimeUtc , x.StopTimeUtc, x.CallingStationId, x.IpAddress}).ToList() }, JsonRequestBehavior.AllowGet);
}
when action return the json to view, it raise a error of datatable
DataTables warning: table id={id} - Ajax error
I think you should try to do like bellow on one of your Datatable Option.
$('#example').dataTable( {
"destroy": true
} );
It caused by reinitialising datatable as you see on the error message.
The destroy option is for it.
I am using iCheck plug-in with datatable.js in my web application.
I use a ajax request to databind this table.
Please see my code below.
Html
<table id="tblCountry" class="table table-striped table-bordered table-hover table-highlight table-checkable"
data-display-rows="10"
data-info="true"
data-search="true"
data-paginate="true" >
<thead>
<tr>
<th class="checkbox-column" style="min-width: 50px;">
<input id="thCheckBox" type="checkbox" class="icheck-input" />
</th>
<th>Id</th>
<th style="min-width: 100px;">Country</th>
</tr>
</thead>
</table>
Script
ajaxUrl = '#Url.Action("GetTestCountryList", "Invoice")';
dtTable = $("#tblCountry").dataTable({
sAjaxSource: ajaxUrl,
aoColumns: [
{
"sClass": "checkbox-column",
bSortable: false,
"mRender": function (data, type, full) {
return '<input type="checkbox" onclick="check(this)" class="icheck-input">';
}
},
{ sTitle: "Id", bSortable: false, bVisible: false, },
{ sTitle: "Name", bSortable: true, },
],
});
Source
public ActionResult GetTestCountryList()
{
List<Country> lstCountry = new List<Country>();
lstCountry.Add(new Country { Id = 1, Name = "India" });
lstCountry.Add(new Country { Id = 2, Name = "USA" });
lstCountry.Add(new Country { Id = 3, Name = "France" });
lstCountry.Add(new Country { Id = 4, Name = "Germiny" });
lstCountry.Add(new Country { Id = 5, Name = "Britan" });
return Json(new
{
aaData = lstCountry.Select(e => new string[]
{
"",
e.Id.ToString(),
e.Name
}).ToArray()
}, JsonRequestBehavior.AllowGet);
}
My problem is the check box style is only applied in the header not applied in the rows. Is there any fault in my code?
You need to call icheck from the datatables DrawCallBack - I had the same issue...
$('.ajax-datatable').dataTable({
responsive: false,
order: [],
sPaginationType: "simple_numbers",
bJQueryUI: true,
bProcessing: false,
bServerSide: true,
bStateSave: true,
sAjaxSource: $('.ajax-datatable').data('source'),
"columnDefs": [
{ "orderable": false, "targets":[$('.ajax-datatable').data('targets')]}
],
"fnPreDrawCallback": function() {
$.blockUI({ message: '<img src="<%= asset_path 'ajax-loader.gif'%>" />',css: { backgroundColor: 'none', border: '0px'} });
return true;
},
"fnDrawCallback": function() {
$.unblockUI();
icheck();
}
});
add a checked attribute like this
return '<input type="checkbox" onclick="check(this)" class="icheck-input" checked>';