Jquery Datatable data is not getting aligned with the table header - c#

using JQuery Datatable we are trying to row grouping and facing the below issue - table header and data is not getting aligned properly as shown in the below image tried setting css property,adjusting the width of the header. but datatable is not taking the width.DataTable grid width issue screenshot
below is the sample code by which we populate the data grid
cshtml code
<html>
<div hidden id="div-summary-table-SelfApp">
<table class="table table-border table-striped table-bordered dt-responsive" width="140%" cellspacing="0" id="summary-table-selfApp" style="border-bottom: none !important;">
<thead>
<tr>
<th colspan="7">#SharedLocalizer.GetLocalizedHtmlString("eventinfo")</th>
<th colspan="6">#SharedLocalizer.GetLocalizedHtmlString("roleInformation")</th>
</tr>
<tr>
<th rowspan="2">#SharedLocalizer.GetLocalizedHtmlString("eventID")</th>
<th rowspan="2">#SharedLocalizer.GetLocalizedHtmlString("eventname")</th>
<th rowspan="2">#SharedLocalizer.GetLocalizedHtmlString("eventdate")</th>
<th rowspan="2">#SharedLocalizer.GetLocalizedHtmlString("holdingarea")</th>
<th rowspan="2">#SharedLocalizer.GetLocalizedHtmlString("nameofapplicant")</th>
<th rowspan="2">#SharedLocalizer.GetLocalizedHtmlString("event_applicationstatus")</th>
<th rowspan="2">#SharedLocalizer.GetLocalizedHtmlString("event_reportingstatus")</th>
<th rowspan="2">#SharedLocalizer.GetLocalizedHtmlString("performername")</th>
<th rowspan="2">#SharedLocalizer.GetLocalizedHtmlString("nameoffacility")</th>
<th rowspan="1" colspan="4">#SharedLocalizer.GetLocalizedHtmlString("status")</th>
</tr>
<tr>
<th>#SharedLocalizer.GetLocalizedHtmlString("policy")</th>
<th>#SharedLocalizer.GetLocalizedHtmlString("arrangementoftranspotation")</th>
<th>#SharedLocalizer.GetLocalizedHtmlString("slidebeforetheevent")</th>
<th>#SharedLocalizer.GetLocalizedHtmlString("slideontheday")</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</html>
`
js code
`
$("#summary-table-selfApp").DataTable({
"dom": '<"top"li>rt<"bottom"p>',
"scrollX": true,
"ajax": {
"url": "test/data",
"type": "POST",
"dataType": "JSON",
"data": function (filterParam) {
filterParam.EventID = EventIDSA;
filterParam.EventName = EventNameSA;
filterParam.Applicant = ApplicantSA;
filterParam.ApplicantBranchName = ApplicantBranchSA;
filterParam.ApplicantDepartmentName = drpDeptSelfApp;
filterParam.SearchOrganization = OrganizationSA;
filterParam.Status = StatusSA;
filterParam.EventType = EventTypeSA;
filterParam.EventSubType = EventSubTypeSA;
filterParam.HowToHold = HowToHoldSA;
filterParam.HoldingArea = HoldingAreaSA;
filterParam.ProductName = ProductNameSA;
filterParam.HoldingFormat = HoldingFormatSA;
filterParam.Role = isUserId;
filterParam.ExpertName = ExpertNameSA;
filterParam.FacilityName = FacilityNameSA;
filterParam.CostCenter = CostCenterSa;
filterParam.ActivityWBSName = ActivityWBSSA;
filterParam.SearchType = SearchType;
filterParam.UserID = isLoggedId;
filterParam.EventFromDate = EventFrmDate;
filterParam.EventToDate = EventToDate;
filterParam.PersonInCharge = PersonInChargeSA;
filterParam.IsExceptionApp = ExceptionApp;
filterParam.ReportApproval = ReportApproval;
filterParam.MonitoringFrmDate = MonitoringFrmDate;
filterParam.MonitoringToDate = MonitoringToDate;
filterParam.RefetchData = refetchData;
filterParam.SlideBeforeEvent = SlideBeforeEvent;
filterParam.SlideOnTheDay = SlideOnTheDay;
filterParam.ApplicantBusinessUnit = BusinessUnitSA;
},
},
"bServerSide": true,
"pagingType": "full_numbers",
"bFilter": false,
"language": {
"search": "Filter records:",
"paginate": {
"first": "<<",
"previous": "<",
"next": ">",
"last": ">>"
},
"emptyTable": "レコードがありません。",
"lengthMenu": "表示件数 _MENU_/ページ",
"info": "<b>_TOTAL_</b> 件のうち <b>_START_</b> から <b>_END_</b> 件 を表示",
"infoEmpty": ""
},
"rowsGroup": [0, 1, 2, 3, 4, 5, 6],
"drawCallback": function (settings) {
refetchData = false;
if ($(this).find('.dataTables_empty').length == 1) {
$('.dataTables_paginate').hide();
$('.dataTables_info').hide();
}
else {
$('.dataTables_paginate').show();
$('.dataTables_info').show();
}
},
"columns": [
{ "data": "eventIdUrl", "name": "eventIdUrl", "autoWidth": true },
{ "data": "eventName", "name": "eventName", "autoWidth": true },
{ "data": "eventDateStr", "name": "eventDateStr", "autoWidth": true },
{ "data": "holdingArea", "name": "holdingArea", "autoWidth": true },
{ "data": "applicant", "name": "applicant", "autoWidth": true },
{ "data": "eventAppStatus", "name": "eventAppStatus", "autoWidth": true },
{ "data": "eventRepStatus", "name": "eventRepStatus", "autoWidth": true },
{ "data": "performerName", "name": "performerName", "autoWidth": true },
{ "data": "workfacility", "name": "workfacility", "autoWidth": true },
{
"name": "policy", "autoWidth": true,
"data": function (row, type, val, meta) {
return '<a class="properName" target="_blank" href="/contract/contractdetails?EventExpertId=' + row.expertId + '">' + row.policy + '</a>'
}
},
{
"name": "transportation", "autoWidth": true,
"data": function (row, type, val, meta) {
return '<a class="properName" target="_blank" href="/Travel/ParticipantTravelRequestForm?eventId=' + row.eventId + '&expert_id=' + row.expertId + '">' + row.transportation + '</a>'
}
},
{
"name": "slideStatusBefore", "autoWidth": true,
"data": function (row, type, val, meta) {
return '<a class="properName" target="_blank" href="' + srsSlideUrl + row.eventId + '&expert_id=' + row.slideExpertId + '">' + row.slideStatusBefore + '</a>'
}
},
{
"name": "slideStatusAfter", "autoWidth": true,
"data": function (row, type, val, meta) {
return '<a class="properName" target="_blank" href="' + srsSlideUrl + row.eventId + '&expert_id=' + row.slideExpertId + '">' + row.slideStatusAfter + '</a>'
}
}
]
});`
could you help how to set the data gets align with the header dynamically

Related

Columns Width are different in most chrome versions and Firefox

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.

Drop down selected value to Edi in MVC

Running MVC application in visual studio. this application based on Timesheet management. i have different project drop down list . i have attached screen shot for your reference
Before Submit :
after if user enter wrong if trying change time looks
Concrete Class :
public void UpdateEmployee(TimeSheetDetails timesheetupdate)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TimesheetDBEntities"].ToString()))
{
SqlCommand cmd = new SqlCommand("Usp_UpdateTimesheet", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TimeSheetID ",timesheetupdate.TimeSheetID);
cmd.Parameters.AddWithValue("#DaysofWeek", timesheetupdate.DaysofWeek);
cmd.Parameters.AddWithValue("#Hours", timesheetupdate.Hours);
cmd.Parameters.AddWithValue("#Period", timesheetupdate.Period);
cmd.Parameters.AddWithValue("#ProjectID", timesheetupdate.ProjectID);
cmd.Parameters.AddWithValue("#UserID", timesheetupdate.UserID);
cmd.Parameters.AddWithValue("#CreatedOn", timesheetupdate.CreatedOn);
cmd.Parameters.AddWithValue("#TimeSheetMasterID", timesheetupdate.TimeSheetMasterID);
cmd.Parameters.AddWithValue("#TotalHours",timesheetupdate.Hours);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Edit Controller Action :
// GET: Employee/EditEmpDetails/5
public ActionResult EditTimesheet(int id)
{
TimeSheetConcrete EmpRepo = new TimeSheetConcrete();
return View(EmpRepo.TimesheetDetailsbyTimeSheetMasterID().Find(Emp => Emp.TimeSheetID == id));
}
// POST: Employee/EditEmpDetails/5
[HttpPost]
public ActionResult EditTimesheet(int id, EmpModel obj)
{
try
{
TimeSheetConcrete EmpRepo = new TimeSheetConcrete();
EmpRepo.UpdateEmployee(obj);
return RedirectToAction("GetAllEmpDetails");
}
catch
{
return View();
}
}
My View :
#{
ViewBag.Title = "TimeSheet";
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
<link href="~/Scripts/dataTablesScripts/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="~/Scripts/dataTablesScripts/responsive.bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/dataTablesScripts/jquery.dataTables.min.js"></script>
<script src="~/Scripts/dataTablesScripts/dataTables.bootstrap4.min.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">All TimeSheet</div>
<div class="panel-body">
<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>TimeSheetMasterID</th>
<th>FromDate</th>
<th>ToDate</th>
<th>TotalHours</th>
<th>CreatedOn</th>
<th>TimeSheetStatus</th>
<th>Comment</th>
<th>Details</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#myTable").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/AllTimeSheet/LoadTimeSheetData",
"type": "POST",
"datatype": "json"
},
"columnDefs":
[{
"targets": [0],
"visible": false,
"searchable": false
},
{
"targets": [6],
"searchable": false,
"orderable": false
},
{
"targets": [7],
"searchable": false,
"orderable": false
},
{
"targets": [8],
"searchable": false,
"orderable": false
}
],
"columns": [
{ "data": "TimeSheetMasterID", "name": "TimeSheetMasterID", "autoWidth": true },
{ "data": "FromDate", "name": "FromDate", "autoWidth": true },
{ "data": "ToDate", "name": "ToDate", "autoWidth": true },
{ "data": "TotalHours", "name": "TotalHours", "autoWidth": true },
{ "data": "CreatedOn", "name": "CreatedOn", "autoWidth": true },
{ "data": "TimeSheetStatus", "name": "TimeSheetStatus", "title": "Status", "autoWidth": true },
{ "data": "Comment", "name": "Comment", "title": "Comment", "autoWidth": true },
{
"render": function (data, type, full, meta)
{ return '<a class="btn btn-info" href="/AllTimeSheet/Details/' + full.TimeSheetMasterID + '">View</a>'; }
},
{
data: null, render: function (data, type, row) {
if (row.TimeSheetStatus == "Submitted" || row.TimeSheetStatus == "Rejected") {
return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.TimeSheetMasterID + "'); >Delete</a>";
}
else {
return row.TimeSheetStatus;
}
}
},
{
"render": function (data, type, full, meta) { return '<a class="btn btn-info" href="/TimeSheet/Edit/' + full.TimeSheetMasterID + '">View</a>'; }
},
]
});
});
</script>
<script type="text/javascript">
function DeleteData(ID) {
if (confirm("Are you sure you want to delete ...?")) {
DeleteSheet(ID);
}
else {
return false;
}
}
function DeleteSheet(ID) {
// var url = '#Url.Content("~/TimeSheetID")' + "TimeSheet/Delete";
$.post(url, { TimeSheetMasterID: ID }, function (data) {
if (data) {
oTable = $('#myTable').DataTable();
oTable.draw();
}
else {
alert("Something Went Wrong!");
}
});
}
</script>
if user want selected edit mode dropdown selected value ? i am trying many ways i am getting error . please any one give idea to solve this issues

Icheck style is not applied in ajax databind in datatable

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>';

Populating Jquery Datatables with Webservice

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"
}
]
});
} );

Difficulty in binding JSON data to Jquery Datatable

I am having difficulty in binding JSON data to constuct a data table.
My JSON is of the following:
[
{
"ID": 1,
"Number": "2",
"Name": "Avinash"
},
{
"ID":2,
"Number":"21",
"Name":"XYZ"
},
{
"ID": 3,
"Number": "20",
"Name": "KRR"
}
]
I am binding this to jquery datatable as below:
$(document).ready(function () {
$('#table_id').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": '<%:Url.Action("LoadData","Home")%>'
});
$('#table_id').css("width", "100%")
});
My Table Structure is as follows:
<table id="table_id" border="0" class="display" cellpadding="1" cellspacing="1" align="center">
<thead>
<tr>
<th>ID</th>
<th>Number</th>
<th>Name</th>
</tr>
</thead>
</table>
I am getting error as follows:
Datatables Warning(tableid="table_id"):Requested Unknown Parameter'0' from the datasource for row 0
please help..
public ActionResult LoadData()
{
var Data = new DataTable();
Data=DataModel.LoadData();
var JsonData = JsonConvert.SerializeObject(Data, Formatting.None);
return Json(new
{
aaData = JsonData
}, JsonRequestBehavior.AllowGet);
}
After a short investigation, since your JSON is objects, you should supply the columns definition -
json:
{ "aaData": [
{
"ID": 1,
"Number": "2",
"Name": "Avinash"
},
{
"ID":2,
"Number":"21",
"Name":"XYZ"
},
{
"ID": 3,
"Number": "20",
"Name": "KRR"
}
]}
js:
var oTable = $('#table').dataTable({
"bProcessing": true,
"sAjaxSource": '<%:Url.Action("LoadData","Home")%>',
"aoColumns": [
{ "mData": "ID" },
{ "mData": "Number" },
{ "mData": "Name" }
]
});
See example in datatables source under ajax/objects.html.

Categories

Resources