Okay, so, my issue today is I am trying to return a jquery datatable from a AJAX result, and every time I request the AJAX I am getting the following error:
"DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error"
Here is what my view looks like:
<script type="text/javascript">
$(document).ready(function () {
var oTable = $('#StudentTable').dataTable({
"bServerSide": true,
"sAjaxSource": "Admin/FindStudent",
"bProcessing": true,
"aoColumns": [
{ "sName": "StudentID",
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj) {
return 'View';
}
},
{ "sName": "FirstName" },
{ "sName": "LastName" },
{ "sName": "EmailAddress" }
]
});
});
</script>
<table id="StudentTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And here is the controller:
public ActionResult FindStudent(DataTableParamModel dtParams)
{
//if (Session["IsAdmin"] != "True")
//{
// return View("Login");
//}
var repo = new StudentRepository();
var allStudents = repo.GetAllStudents();
IEnumerable<StudentInfo> filteredStudents;
//Check whether the students should be filtered by keyword
if (!string.IsNullOrEmpty(dtParams.sSearch))
{
//Used if particulare columns are filtered
var fnameFilter = Convert.ToString(Request["sSearch_1"]);
var lnameFilter = Convert.ToString(Request["sSearch_2"]);
var emailFilter = Convert.ToString(Request["sSearch_3"]);
//Optionally check whether the columns are searchable at all
var isFNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
var isLNameSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
var isEmailSearchable = Convert.ToBoolean(Request["bSearchable_3"]);
filteredStudents = repo.GetAllStudents()
.Where(c => isFNameSearchable && c.FirstName.ToLower().Contains(dtParams.sSearch.ToLower())
||
isLNameSearchable && c.LastName.ToLower().Contains(dtParams.sSearch.ToLower())
||
isEmailSearchable && c.EmailAddress.ToLower().Contains(dtParams.sSearch.ToLower()));
}
else
{
filteredStudents = allStudents;
}
var isFNameSortable = Convert.ToBoolean(Request["bSortable_1"]);
var isLNameSortable = Convert.ToBoolean(Request["bSortable_2"]);
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
Func<StudentInfo, string> orderingFunction = (c => sortColumnIndex == 1 && isFNameSortable ? c.FirstName :
sortColumnIndex == 2 && isLNameSortable ? c.LastName :
"");
var sortDirection = Request["sSortDir_0"]; // asc or desc
if (sortDirection == "asc")
filteredStudents = filteredStudents.OrderBy(orderingFunction);
else
filteredStudents = filteredStudents.OrderByDescending(orderingFunction);
var displayedStudents = filteredStudents.Skip(dtParams.iDisplayStart).Take(dtParams.iDisplayLength);
var result = from c in displayedStudents select new[] { Convert.ToString(c.StudentID), c.FirstName, c.LastName, c.EmailAddress };
JsonResult results = Json(new
{
sEcho = dtParams.sEcho,
iTotalRecords = allStudents.Count(),
iTotalDisplayRecords = filteredStudents.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
return View(results);
}
When using JSONLint, it spits out
Parse error on line 1:
<headid="Head1"><sty
^
Expecting '{', '['
Any ideas?
try to return Json object:
return Json(new {
sEcho = dtParams.sEcho,
iTotalRecords = allStudents.Count(),
iTotalDisplayRecords = filteredStudents.Count(),
aaData = result
}, JsonRequestBehavior.AllowGet);
resource
Related
In my app I need to loop through my Knockout observable array of objects with observable properties. This is so I can post each object back to the server.
I can access my model but I can not access the child elements, which I would like to post back to the server.
My client code is
self.postAllReqs = function(self) {
self.error(''); // Clear error message
var model = ko.toJSON(self.Reqs); // convert to json
for (var item in model) {
ajaxHelper(reqsUri, 'POST', item).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
})
}
}
How do I access the child element please?
Extract of my View Model
function ReqsTest(rt) {
rt = rt || {};
var self = this;
self.id = ko.observable(rt.ID || 0);
self.requisition = ko.observable(rt.Requisition || "");
self.reqnStatus = ko.observable(rt.ReqnStatus || "");
self.dateReqnRaised = ko.observable(rt.DateReqnRaised|| null);
self.reqnValue = ko.observable(rt.ReqnValue || null);
self.approvedValue = ko.observable(rt.ApprovedValue || null);
self.originator = ko.observable(rt.Originator || "");
self.origName = ko.observable(rt.OrigName || "");
self.origEmail = ko.observable(rt.OrigEmail || "");
self.line = ko.observable(rt.Line || 0.00);
self.indx = ko.observable(rt.INDX || 0);
self.dateReqnRaisedL = ko.observable(rt.DateReqnRaisedL || null);
self.reqStatus = ko.observable(rt.ReqStatus || "");
//self.reqBackground = ko.observable(rt.ReqBackground || "");
//Computed observables
self.reqBackground = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "A") { return "card-heading bg-success text-white"; }
else if (status == "D") { return "card heading bg-secondary"; }
else if (status == "R") { return "card heading bg-warning"; }
else if (status == "E") { return "card heading bg-danger"; }
else {
return "card-heading bg-primary text-white";
}
})
self.reqStatusLabel = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "A") { return "Approved"; }
else if (status == "D") { return "Declined - put on hold"; }
else if (status == "R") { return "Routing On"; }
else if (status == "E") { return "Erase On Syspro"; }
else {
return "Awaiting Approval";
}
})
self.approvalBtn = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "A") { return "css: button btn-secondary "; }
else {
return "btn btn-success ";
}
})
self.approvalBtnLbl = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "W") { return "Approve"; }
else {
return "UnApprove";
}
})
self.declineBtnLbl = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "D") { return "UnDecline"; }
else {
return "Decline";
}
})
self.deleteBtnLbl = ko.computed(function () {
// get variable
var status = self.reqStatus();
if (status == "E") { return "Restore"; }
else {
return "Erase";
}
})
// Functions
//show details alert
$(".btn").on("click", function () {
$(".alert").removeClass("in").show();
$(".alert").delay(200).addClass("in").fadeOut(2000);
});
}
function ReqsViewModel (){
var self = this;
self.Reqs = ko.observableArray([]);
self.error = ko.observable();
var reqsUri = '/api/ReqsTests/';
function ajaxHelper(uri, method, data) {
self.error(''); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllReqs() {
ajaxHelper(reqsUri, 'GET').done(function (data) {
// Build the ReqsTest objects
var reqs = ko.utils.arrayMap(data, function (rt) {
return new ReqsTest(rt);
});
self.Reqs(reqs);
});
}
From what I can tell with the code provided, there is nothing calling the getAllReqs as its a private function withing the ReqsViewModel.
I'm not exactly clear on what your issue is, so I have created a quick demo using your example code to show how you can interact with items in the array.
var app = {};
function ReqsTest(rt, saveItemFn) {
rt = rt || {};
var self = this;
self.id = ko.observable(rt.ID || 0);
self.requisition = ko.observable(rt.Requisition || "");
self.reqnStatus = ko.observable(rt.ReqnStatus || "");
self.dateReqnRaised = ko.observable(rt.DateReqnRaised || null);
self.reqnValue = ko.observable(rt.ReqnValue || null);
self.approvedValue = ko.observable(rt.ApprovedValue || null);
self.originator = ko.observable(rt.Originator || "");
self.origName = ko.observable(rt.OrigName || "");
self.origEmail = ko.observable(rt.OrigEmail || "");
self.line = ko.observable(rt.Line || 0.00);
self.indx = ko.observable(rt.INDX || 0);
self.dateReqnRaisedL = ko.observable(rt.DateReqnRaisedL || null);
self.reqStatus = ko.observable(rt.ReqStatus || "");
//self.reqBackground = ko.observable(rt.ReqBackground || "");
//Computed observables
self.reqBackground = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "A") {
return "card-heading bg-success text-white";
} else if (status == "D") {
return "card heading bg-secondary";
} else if (status == "R") {
return "card heading bg-warning";
} else if (status == "E") {
return "card heading bg-danger";
} else {
return "card-heading bg-primary text-white";
}
})
self.reqStatusLabel = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "A") {
return "Approved";
} else if (status == "D") {
return "Declined - put on hold";
} else if (status == "R") {
return "Routing On";
} else if (status == "E") {
return "Erase On Syspro";
} else {
return "Awaiting Approval";
}
})
self.approvalBtn = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "A") {
return "css: button btn-secondary ";
} else {
return "btn btn-success ";
}
})
self.approvalBtnLbl = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "W") {
return "Approve";
} else {
return "UnApprove";
}
})
self.approve = function() {
if (self.reqStatus() == 'W') {
self.reqStatus("A");
} else {
self.reqStatus("W");
}
saveItemFn(self);
}
self.declineBtnLbl = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "D") {
return "UnDecline";
} else {
return "Decline";
}
})
self.deleteBtnLbl = ko.computed(function() {
// get variable
var status = self.reqStatus();
if (status == "E") {
return "Restore";
} else {
return "Erase";
}
})
// Functions
//show details alert
$(".btn").on("click", function() {
$(".alert").removeClass("in").show();
$(".alert").delay(200).addClass("in").fadeOut(2000);
});
}
function dataService(serviceUrl) {
var url = serviceUrl;
function getData() {
// do ajax call here
return {
done: function(fn) {
return fn(app.externalData);
}
}
}
function saveItem(item) {
// add posting to server here.
alert("Saving item: " + item.id());
}
return {
getData: getData,
saveItem: saveItem,
};
}
function ReqsViewModel(dataService) {
var reqsUri = 'api/ReqsTests/';
var self = this;
self.Reqs = ko.observableArray([]);
self.error = ko.observable();
self.getAllReqs = getAllReqs;
function getAllReqs() {
dataService.getData().done(function(data) {
// Build the ReqsTest objects
var reqs = ko.utils.arrayMap(data, function(rt) {
return new ReqsTest(rt, dataService.saveItem);
});
self.Reqs(reqs);
});
}
}
app.dataService = dataService;
app.externalData = [{
ID: 1,
Requisition: "Requisition 1",
ReqnStatus: "A",
DateReqnRaised: "2019-01-01T11:00:00+11:00",
ReqnValue: 200.24,
ApprovedValue: 200,
Originator: "Slartibartfast",
OrigName: "Requisition 1",
OrigEmail: "test#test.com",
Line: 1.1,
INDX: 1,
DateReqnRaisedL: "2019-01-01T11:00:00+11:00",
ReqStatus: "A"
}, {
ID: 2,
Requisition: "Requisition 2",
ReqnStatus: "W",
DateReqnRaised: "2019-01-02T11:00:00+11:00",
ReqnValue: 300.24,
ApprovedValue: 300,
Originator: "Slartibartfast",
OrigName: "Requisition 2",
OrigEmail: "test#test.com",
Line: 2.2,
INDX: 2,
DateReqnRaisedL: "2019-01-02T11:00:00+11:00",
ReqStatus: "W"
}];
var vm = new ReqsViewModel(app.dataService("/api/reqs/"));
vm.getAllReqs();
ko.applyBindings(vm);
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Requistion</th>
<th>Raised</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: Reqs">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: requisition"></td>
<td data-bind="text: dateReqnRaised"></td>
<td><button class="btn btn-primary" data-bind="css: approvalBtn, text: approvalBtnLbl, click: approve">Approve</button></td>
</tr>
</tbody>
</table>
I have only one table in database with 2 million records , i want the user to be able to browse the data and also have the ability to sort data and filter it.
also user should be able to navigate between pages
Here is my MVC controller
public class AssetController : Controller
{
private ApplicationDbContext _dbContext;
public ApplicationDbContext DbContext
{
get
{
return _dbContext ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();
}
private set
{
_dbContext = value;
}
}
public AssetController()
{
}
public AssetController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
// GET: Asset
public ActionResult Index()
{
return View();
}
public ActionResult Get([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel)
{
IEnumerable<Asset> query = DbContext.Assets;
var totalCount = query.Count();
#region Filtering
// Apply filters for searching
if (requestModel.Search.Value != string.Empty)
{
var value = requestModel.Search.Value.Trim();
query = query.Where(p => p.Barcode.Contains(value) ||
p.Manufacturer.Contains(value) ||
p.ModelNumber.Contains(value) ||
p.Building.Contains(value)
);
}
var filteredCount = query.Count();
#endregion Filtering
#region Sorting
// Sorting
var sortedColumns = requestModel.Columns.GetSortedColumns();
var orderByString = String.Empty;
foreach (var column in sortedColumns)
{
orderByString += orderByString != String.Empty ? "," : "";
orderByString += (column.Data) + (column.SortDirection == Column.OrderDirection.Ascendant ? " asc" : " desc");
}
query = query.OrderBy(orderByString == string.Empty ? "BarCode asc" : orderByString);
#endregion Sorting
// Paging
query = query.Skip(requestModel.Start).Take(requestModel.Length);
var data = query.Select(asset => new
{
AssetID = asset.AssetID,
BarCode = asset.Barcode,
Manufacturer = asset.Manufacturer,
ModelNumber = asset.ModelNumber,
Building = asset.Building,
RoomNo = asset.RoomNo,
Quantity = asset.Quantity
}).ToList();
return Json(new DataTablesResponse(requestModel.Draw, data, filteredCount, totalCount), JsonRequestBehavior.AllowGet);
}
}
and below is index.cshtml
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary list-panel" id="list-panel">
<div class="panel-heading list-panel-heading">
<h1 class="panel-title list-panel-title">Properties</h1>
</div>
<div class="panel-body">
<table id="datatable" class="table table-striped table-bordered" style="width:100%;">
<thead>
<tr>
<th>BarCode</th>
<th>Manufacturer</th>
<th>Building</th>
<th>Quantity</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
var datatableInstance = $('#datatable').DataTable({
serverSide: true,
processing: true,
"ajax": {
"url": "#Url.Action("Get","Asset")"
},
lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
columns: [
{ 'data': 'BarCode' },
{ 'data': 'Manufacturer' },
{
'data': 'Building',
'searchable': true,
},
{
'data': 'Quantity',
'searchable': true,
'render': function (Quantity) {
return "$ " + Quantity;
}
},
],
});
});
</script>
}
I used JQuery data-tables , code is working fine if i have small number of rows - less than 100000 , but if i have large number of rows , it becomes very bad
It takes too long in the following line
var filteredCount = query.Count();
How can i enhance the performance
In my opinion, instead doing "var totalCount = query.Count();" try to make an sql statement with a count over the table, probably you will get a better perfomance.
var totalCount = _context.SqlQuery("Select count(0) from yourTable").FirstOrDefault();
I havenĀ“t tested the perfomance with Count(), but with Distinc() the difference is remarkable.
Hope it helps
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult LoadData()
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int totalRecord = 0;
using (ACETeaEntities db = new ACETeaEntities())
{
var v = (from item in db.Drinks_Category select item);
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
v = v.OrderBy(sortColumn + " " + sortColumnDir);
}
totalRecord = v.Count();
var data = v.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFilterd = totalRecord, recordsTotal = totalRecord, data = data }, JsonRequestBehavior.AllowGet);
}
}
}
View:
<script src="~/Scripts/jquery-1.7.2.js" ></script>
<script src="~/Scripts/DataTables/jquery.dataTables.js" ></script>
<link rel="stylesheet" type="text/css" href="~/Content/DataTables/css/jquery.dataTables.css">
<script>
$(document).ready(function () {
$('#example').dataTable({
"processing": true,
"serverSide": true,
"filter": true,
"ordermulti": false,
"ajax": {
"url": "/Home/LoadData",
"type": "POST",
"dataType": "json"
},
"columns": [
{ "data": "Name_category", "autoWidth": true },
{ "data": "Id_category", "autoWidth": true },
{ "data": "Parent", "autoWidth": true }
]
});
});
</script>
<div style="margin:30px;">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr style="text-align:left;">
<th>Id</th>
<th>Name</th>
<th>Parent</th>
</tr>
</thead>
<tfoot>
<tr style="text-align:left;">
</tr>
</tfoot>
</table>
</div>
My code bugs at: v = v.OrderBy(sortColumn + " " + sortColumnDir);
Can someone help me fix it?
When using the OrderBy method you need to pass the column you want to sort by as a property and use a different method for defining the direction
For example:
v = v.OrderBy(i => i.myColumn);
v = v.OrderByDescending(i => i.myColumn);
Since you are getting your parameters as a string, you have two options:
1) You can build your function first before passing it as well as define your direction
For example:
if (sortColumn == "myColumn")
{
myOrderByFunc = i => i.myColumn;
}
elseif (sortColumn == "myOtherColumn")
{
myOrderByFunc = i => i.myOtherColumn;
}
if (direction == "asc")
{
v = v.OrderBy(myOrderByFunc);
}
elseif (direction == "desc")
{
v = v.OrderByDescending(myOrderByFunc);
}
2) You can use the System.Linq.Dynamic library available here to use strings directly in the linq query (as you are doing now)
Note that you can also try the more updated library System.Linq.Dynamic.Core which does support OrderBy and also ThenBy.
i have my jquery like,
$(document).ready(function () {
$('#NotAllotedStudentsGrid').jtable({
title: 'Allot to Students below',
paging: true,
pageSize: 5,
sorting: true,
defaultSorting: 'Name ASC',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkbo.xes on first column
actions: {
listAction: '#Url.Action("NotAllotedStudentsList")',
//deleteAction: '#Url.Action("DeleteStudent")',
//updateAction: '#Url.Action("UpdateStudent")',
//createAction: '#Url.Action("CreateStudent")'
},
fields: {
UserNo: {
key: true,
create: false,
edit: false,
list: false
},
Name: {
title: 'Name',
width: '15%'
},
Batch: {
title: 'Batch',
},
EmailAddress: {
title: 'Email address',
},
ContactNo: {
title: 'Contact No',
type: 'textarea',
}
}
});
//Load student list from server
$('#NotAllotedStudentsGrid').jtable('load');
$('#SearchFor').button().click(function () {
var SearchForValue = $("#NotAllotedStudentsList").val();
var StudentInputTypeValue = $("#InputType").val();
var options = {};
options.type = "POST";
options.url = "/Dashboard/NotAllotedStudentsList/";
options.data = JSON.stringify({ model: { SearchFor: SearchForValue, StudentInputType: StudentInputTypeValue } });
options.dataType = "json";
options.contentType = "application/json";
$.ajax(options);![enter image description here][1]
});
i have my controller like,
public ActionResult NotAllotedStudentsList(AllotQuestionSet model,int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
List<TutorStudentsGridModel> tutorStudentsGridModelList = new List<TutorStudentsGridModel>();
User userDetails = _sessionHelper.Get<User>(KrackemSessionConstants.UserDetails);
StudentResponse studentListResponse = new StudentResponse();
int questionSetNo = Int32.Parse(_sessionHelper.Get<string>(KrackemSessionConstants.QuestionSetNo));
if (model.SearchFor == null)
{
StudentRequest studentRequest = new StudentRequest
{
TutorUserNo = userDetails.UserNo,
QuestionSetNo = questionSetNo
};
studentListResponse = _questionSetServiceHelper.GetNotAllottedStudentsByTutorNo(studentRequest);
}
//Get Not Allotted Students By Name
if (model.SearchFor != null && model.StudentInputType == StudentInputType.Name)
{
StudentRequest studentRequest = new StudentRequest
{
TutorUserNo = userDetails.UserNo,
QuestionSetNo = questionSetNo,
InputString = model.SearchFor
};
studentListResponse = _questionSetServiceHelper.GetNotAllottedStudentsByName(studentRequest);
}
foreach (StudentContract studentDetails in studentListResponse.StudentList)
{
TutorStudentsGridModel tutorStudentsGridModel = MappingEngineFactory.GetMappingEngine().Map<StudentContract, TutorStudentsGridModel>(
studentDetails);
tutorStudentsGridModel.Id = studentDetails.UserNo;
tutorStudentsGridModelList.Add(tutorStudentsGridModel);
}
if (jtSorting != null)
tutorStudentsGridModelList = ControllerHelper.SortList(jtSorting, tutorStudentsGridModelList);
tutorStudentsGridModelList = jtPageSize > 0 ? tutorStudentsGridModelList.Skip(jtStartIndex).Take(jtPageSize).ToList() : tutorStudentsGridModelList.ToList();
return Json(new { Result = "OK", Records = tutorStudentsGridModelList, TotalRecordCount = studentListResponse.StudentList.Count() });
}
Initially, the page with grid get loaded from server with the list of students with fields i.name ii.batch iii.email iv.contact_no, after selecting "name" from dropdown and entered a name in textbox then clicking the search button for search , the search results should display. But its displaying old grid. kindly tell me how to display the search result from the grid using jquery.
I am trying to display Dates on to the jQuery Datatables but I get the following error "Requested unknown parameter 'DateTimes' from the data source for row 0 and then it displays all other columns with data but leaves the DateTimes column empty.
Here's my View code the for jQuery Datatable:
<script>
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "TopPlayedInVenueList2",
"bProcessing": true,
"aoColumns": [
{ "mData": "TrackID" },
{ "mData": "DateTimes", "sType": 'date' },
{ "mData": "TrackName" },
{ "mData": "ArtistName" },
{ "mData": "Times" }
]
});
});
</script>
<table id="myDataTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>Date</th>
<th>Track Name</th>
<th>Artist Name</th>
<th>Times</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here's my server-side Controller code for converting the Date:
var listOrder = daa.Where(i => i.Date >= Convert.ToDateTime(StartDate) && i.Date <= Convert.ToDateTime(EndDate)).ToList();
Edit: TopPlayedInVenueList2 Action Method Controller Code:
public ActionResult TopPlayedInVenueList2(jQueryDataTableParamModel param, string StartDate = "", string EndDate = "")
{
try
{
if (Request.IsAuthenticated == true)
{
string Path = #"C:\\5Newwithdate-1k.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
con.Close();
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
TopPlayed top = new TopPlayed()
{
TrackID = Convert.ToInt32(p.Field<double>("TrackID")),
Date = p.Field<DateTime>("DateTimes"),
TrackName = p.Field<string>("TrackName"),
ArtistName = p.Field<string>("ArtistName"),
Times = Convert.ToInt32(p.Field<double>("Times"))
};
daa.Add(top);
}
var newlist = daa.OrderBy(i => i.Times).ToList();
if (!string.IsNullOrEmpty(param.sSearch))
{
newlist = daa;
daa.Where(c => c.TrackName.Contains(param.sSearch)
||
c.ArtistName.Contains(param.sSearch)
||
c.TrackName.Contains(param.sSearch));
}
else
{
newlist = daa;
}
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
Func<Company, string> orderingFunction = (c => sortColumnIndex == 1 ? c.Name :
sortColumnIndex == 2 ? c.Address :
c.Town);
var sortDirection = Request["sSortDir_0"]; // asc or desc
if (sortDirection == "asc")
newlist = daa.OrderBy(i => i.Times).ToList();
else
newlist = daa.OrderByDescending(i => i.Times).ToList();
var displayedCompanies = newlist;
// var listOrder = daa.Where(i => i.Date >= Convert.ToDateTime(StartDate) && i.Date <= Convert.ToDateTime(EndDate)).ToList();
return Json(new { sEcho = param.sEcho,
iTotalRecords = newlist.ToList().Count(),
iTotalDisplayRecords = newlist.ToList().Count(),
aaData = daa
}, JsonRequestBehavior.AllowGet);
}
Any help would be a great help :) Thanks in advanced.
Collection object does not have DateTime property. It has Date property.
Change DT configuration accordingly:
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "TopPlayedInVenueList2",
"bProcessing": true,
"aoColumns": [
{ "mData": "TrackID" },
{ "mData": "Date", "sType": 'date' },
{ "mData": "TrackName" },
{ "mData": "ArtistName" },
{ "mData": "Times" }
]
});
How to Display Date in "dd/MM/yyyy" format in Datatable js data table column.
<script>
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "TopPlayedInVenueList2",
"bProcessing": true,
"aoColumns": [
{ "mData": "TrackID" },
{ "mData": "DateTimes", "sType": 'date' },
{ "mData": "TrackName" },
{ "mData": "ArtistName" },
{ "mData": "Times" }
],
"columnDefs": [
{
"render": function (data, type, row) {
debugger;
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(data);
var date = new Date(parseFloat(results[1]))
var month = date.getMonth() + 1;
var day = date.getDate();
return (day > 9 ? day : "0" + day) + "/" + (month > 9 ? month : "0" + month) + "/" + date.getFullYear();
},
"targets": 1
}
]
});
</script>
I hope this will help.