mDataProp DateTime format issue - c#

Hi I have a mDataProp DateTime formatting issue. Basically I want to display the date in one column and the time in another.
But as I understand it the mDataProp is directly related to your model, which does not have a time property just a adate......
Controller
var result = from a in data
select new
{
appointmentDate = a.AppointmentDate.ToShortDateString(),//.ToString("g"),
appointmentTime = a.AppointmentDate.ToLocalTime().ToString("t"),
appointmentName = a.AppointmentType.AppName,
appointmentID = a.AppointmentID
};
//Return Json data for Datatable
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = total,
iTotalDisplayRecords = total,
aaData = result
});
View
<script>
$(document).ready(function () {
var urlRequest = $('#apptTable').data("request-url");
var detailRequest = $('#apptTable').data("detail-url");
$('#apptTable').dataTable({
"bSort": false,
"bServerSide": true,
"sAjaxSource": urlRequest,
"sServerMethod": "POST",
"bProcessing": true,
"bFilter": false,
"aoColumns": [
{ "mDataProp": "appointmentDate" },
{ "mDataProp": "appointmentDate" },
{ "mDataProp": "appointmentName" },
{
"mDataProp": "appointmentID",
"fnRender": function (oObj) {
return 'Details';
}
}
]
});
});
</script>
I cannot create a second variable called appointmentDate in the controller, so I'll have to format in the view.
Any ideas?

Related

jQuery Datatable not sorting in asp.net webform

I have used jquery datatable Server-side processing in my application (asp web form ), after the data returned, paging, searching and sorting do not work. I've read several cases here on the forum of similar or equal problems, but I still haven't been able to solve mine. Could you look at my code, please?
datatable
<script type="text/javascript">
$(document).ready(function () {
$("#stockDatatable").DataTable({
"processing": true, //show processing message
"serverSide": true, //is server side
"filter": true, //allow filter
"ajax": {
"url": "WebForm2.aspx/GetData", //endpoint to get data
"contentType": "application/json",
"type": "GET",
"dataType": "JSON",
"data": function (d) {
return d;
},
"dataSrc": function (json) {
json.draw = json.d.draw;
json.recordsTotal = json.d.recordsTotal;
json.recordsFiltered = json.d.recordsFiltered;
json.data = json.d.data;
var return_data = json.d.data;
return return_data;
}
},
"columns": [ // columns to populate
{ "data": "Id" },
{ "data": "Code"},
{ "data": "Type" },
{ "data": "Text_Description" },
{ "data": "Date_Time" },
{ "data": "Date_Created"},
{ "data": "Added_by" },
],
});
});
</script>
Code Behind (Webform2.cs)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static object GetData()
{
DataTables result = new DataTables();
using (var db = new MunchData())
{
string search = HttpContext.Current.Request.Params["search[value]"];
string draw = HttpContext.Current.Request.Params["draw"];
string order = HttpContext.Current.Request.Params["order[0][column]"];
string sortColumnDirection = HttpContext.Current.Request.Params["order[0][dir]"];
int startRec = Convert.ToInt32(HttpContext.Current.Request.Params["start"]);
int pageSize = Convert.ToInt32(HttpContext.Current.Request.Params["length"]);
string start = HttpContext.Current.Request.Params["start"];
int skip = start != null ? Convert.ToInt32(start) : 0;
var data = db.Machineinfoes.OrderByDescending(p => p.Id).ToList();
int totalRecords = data.Count;
int recFilter = data.Count;
result.draw = Convert.ToInt32(draw);
result.recordsTotal = totalRecords;
result.recordsFiltered = recFilter;
result.data = data.Skip(skip).Take(pageSize).ToList();
}
return result;
}

How to pass a fetched value from back-end to front-end in asp.net mvc5?

I have a stored procedure that equates and gets the occupancy rate of a room. I want to fetch the data from the back-end using JSon and display the output data of the stored procedure in the front-end code. But the output data only sticks at the Business Layer. How can i call it from my Controller using Json?
Here is my code
In my Controller
public JsonResult GetoccupancyRate()
{
string _connectionString = rAppSetting.ConnectionString;
try
{
IList<Hotel> _currentOccupancyRateList = rHotelFacade.GetOccupancyRate(HotelIDCookie, DateTime.Now, _connectionString);
IList<Hotel> _yesterdayOccupancyRateList = rHotelFacade.GetOccupancyRate(HotelIDCookie, DateTime.Now.AddDays(-1), _connectionString);
return Json(new
{
success = true,
message = "Success",
yesterdayOccupancyRate = _yesterdayOccupancyRateList,
currentOccupancyRate = _currentOccupancyRateList
},JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new
{
success = false,
message = ex.Message,
currentOccupancyRate = "",
yesterdayOccuoancyRate = ""
}, JsonRequestBehavior.AllowGet);
}
}
Javascript
myapp.factory("occupancyRateService", ['$http', function ($http) {
this.LoadOccupancyRate = function () {
return $http.get("/Dashboard/GetOccupancyRate", {});
};
return this;}]);
myapp.controller('MainController', ['$scope', 'dashboardService', 'occupancyRateService', function ($scope, dashboardService, occupancyRateService) {
$scope.myChart = {
type: 'google.charts.Bar',
options: {},
data: {}
};
$scope.loadOccupancyRateDetails = function () {
occupancyRateService.LoadOccupancyRate().success(function (result) {
if (result.success)
{
var currentOccupancyRateData = result.currentOccupancyRate;
var yesterdayOccupancyRateData = result.yesterdayOccupancyRate;
console.log(result.currentOccupancyRate);
console.log(result.yesterdayOccupancyRate);
//console.log(yesterdayResultData)
if (currentOccupancyRateData || yesterdayOccupancyRateData === null)
{
google.charts.load('current', { 'packages': ['line', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Day', 'Rate'],
['Yesterday', 0],
['Today', 0]
]);
var options = {
chart: {
//title:'Occupancy Rate',
},
bars: 'vertical',
hAxis: { format: 'none', gridlines: { count: 5 } },
vAxis: { format: '.######%' },
height: 180,
//width: 100%,
colors: ['#1b9e77']
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
$(window).resize(function () {
drawChart();
});
}
else
{
google.charts.load('current', { 'packages': ['line', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Day', 'Rate'],
['Yesterday', currentOccupancyRateData],
['Today', yesterdayOccupancyRateData]
]);
//function drawChart() {
// var data = google.visualization.arrayToDataTable([ORData]);
var options = {
chart: {
//title:'Occupancy Rate',
},
bars: 'vertical',
hAxis: { format: 'none', gridlines: { count: 5 } },
vAxis: { format: '.################%' },
height: 180,
//width: 100%,
colors: ['#1b9e77']
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
$(window).resize(function () {
drawChart();
});
}
}
})
.error(function (error) {
alert(error);
})
};
$scope.loadOccupancyRateDetails();
//<--------------------------------------->
}]);

server side pagination doesn't seem to be working c# asp.net jquery datatables

I am trying to get the pagination to work but it's not working. I have over 90k records in the database but it only displays 50 records as per in the screen shot below:
I am returning the below JSON as per this tutorial and this resolved query:
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = tracks.Count(),
iTotalDisplayRecords = filteredTracks.Count(),
aaData = results
},
JsonRequestBehavior.AllowGet);
}
This is the pagination Controller code:
var displayedTracks = filteredTracks.Skip(param.iDisplayStart).Take(param.iDisplayLength);
Here's my View code of the dataTable:
var oTable = $('#myDataTable').hide(50).fadeIn(10).dataTable({
"oLanguage": {
"sSearch": " "
},
"bAutoWidth": false,
"sAjaxSource": "Ajax_DB",
"deferRender": false,
"bServerSide": true,
"bProcessing": true,
"sScrollY": "333",
"iDisplayLength": 50,
"bPaginate": true,
"bRetrieve": true,
"bDestroy": true,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "mDataProp_": "TrackID", "sWidth": "1%" },
{ "mDataProp_": "AddedDate", "bSortable": false, "sWidth": "1%" },
{ "mDataProp_": "TrackName", "sWidth": "43%" },
{ "mDataProp_": "ArtistName", "sWidth": "30%" },
{ "mDataProp_": "ArtistName", "sWidth": "30%" }
]
});
I don't know what I am doing wrong here, the pagination doesn't seem to work. Could someone please help me on how I can achive this? Thanks in advance.
Its pretty simple mate
Just change your iDisplayLength property's value to your required count i.e 100 or what ever
"iDisplayLength": 100
Refer datatables.net for documentaions which which will help you
Hope it helps
Have you sure your code looks like this :
filteredLeads = filteredLeads.OrderByDescending(orderingFunction);
var DisplayedLeads = filteredLeads.Skip(param.iDisplayStart).Take(param.iDisplayLength);
var result = from c in DisplayedLeads select new string[] { // my columns };
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = leadDetails.Count(),
iTotalDisplayRecords = filteredLeads.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
Let know what is your test results appearing at itotalrecords,iTotalDisplayRecords, aaData while debugging .

No Data Shown On JQGrid

I'm fairly new to MVC and Jquery. for last couple of days I was trying to use Jqgrid http://www.trirand.com/blog/ to show data in my database. I use EF Code first to create my only class 'Author'
public class Author
{
public int AuthorID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return FirstName+ " "+LastName ;
}
}
}
and this is my 'AuthorController' which create Json data:
public ActionResult LinqGridData(string sidx, string sord, int page, int rows)
{
var jsonData = new
{
total = 5,
page = 1,
records = db.Authors.Count(),
rows = db.Authors.Select(a => new
{
id = a.AuthorID,
cell = new { a.AuthorID, a.FirstName, a.LastName }
}
)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I also tried different method to get my Json data:
public ActionResult LinqGridData (string sidx, string sord, int page, int rows)
{
var jsonData = new {
total = 5,
page=1,
records = db.Authors.Count(),
rows = (from a in db.Authors
select new
{
id = a.AuthorID,
cell = new { a.AuthorID, a.FirstName, a.LastName }
}
)
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
and here is my JavaScript, which I use in my view:
$(function () {
$("#list").jqGrid({
url: '/Author/LinqGridData',
datatype:'json',
mtype: 'GET',
colNames:['Author ID', 'First Name', 'Last Name'],
colModel:[
{name:'AuthorID',index:'AuthorID',width:55 },
{name:'FirstName',index:'FirstName',width:90 },
{name:'LastName',index:'LastName',width:80,align:'right' }
],
pager:'#pager',
rowNum: 10,
rowList:[5, 10, 20, 30],
sortname:'AuthorID',
sortorder:'desc',
viewrecords:true,
gridview:true,
caption:'Author List'
});
});
jQuery("#datagrid").jqGrid('navGrid', '#navGrid', { edit: true, add: true, del: true });
I can show the grid with dummy data. with this action method:
public ActionResult GridData(string sidx, string sord, int page, int rows)
{
var jsonData = new
{
total = 1, // we'll implement later
page = 1,
records = 3, // implement later
rows = new[]
{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
new {id = 2, cell = new[] {"2", "15", "Is that a good question?"}},
new {id = 3, cell = new[] {"3", "23", "Why is the sky in the sky?"}}
}
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
the problem is whenever I want to show the data from my database, I only can show the grid itself not the data.
I tried to convert the json data toList() or toArary() before sending to the view, same result. I hope I made myself clear.
any help would be much appreciated.
Have you tried jsonReader with "repeatitems: false" ?
For example:
$("#list").jqGrid({
url: '/Author/LinqGridData',
datatype:'json',
jsonReader: {
repeatitems: false
},
.....
UPDATE:
If you look at the response body returned from your LinqGridData method, it looks like this:
{"total":5,"page":1,"records":1,"rows":
[
{"id":"1","cell":{"AuthorID":"1","FirstName":"Mike","LastName":"Lee"}}, .....
]
}
But I think it should be like this:
{"total":5,"page":1,"records":1,"rows":
[
{"id":"1","cell":{"1", "Mike", "Lee"}}, .....
]
}
Actually this is your "dummy data" version's response body.
I'll post my working example below. In this example, I did not use 'cell' attribute.
At server side:
var myQuery = from t in db.Customers
select t;
var jsonData = new
{
total = totalPages,
page = pageNum,
records = totalRecords,
rows = myQuery.ToList()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
At client side:
{
url: '#Url.Action("GetList")',
datatype: 'json',
jsonReader: {
repeatitems: false
},
mtype: 'GET',
colModel: [
{
name: 'CustomerID', label: 'ID', hidden: false, width: 40, sortable: true
},
{
name: 'CompanyName', label: 'Company', width: 100, align: 'center'
},
]
}
Hope this helps.
I finally managed to show data from my db. the problem was in my query. i use this method for my action method:
public JsonResult LinqGridData (string sidx, string sord, int page, object rows)
{
var authors = (from a in db.Authors select a).ToList();
var jsonData = new {
total = 5,
page=1,
records = db.Authors.Count(),
rows = authors.Select(a => new
{
id = a.AuthorID,
cell = new[] { a.AuthorID.ToString(), a.FirstName, a.LastName }
}
)
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
and i used this in my Javascript:
$(function () {
$("#list").jqGrid({
url: "/Author/LinqGridData",
datatype: "json",
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id:"id"
},
mtype: "GET",
colNames: ["Author ID", "First Name", "Last Name"],
colModel: [
{ name: "AuthorID", key: true, width: 55 },
{ name: "FirstName", width: 80 },
{ name: "LastName", width: 100, align: "right" }
],
pager: "#pager",
rowNum: 10,
rowList: [5, 10, 20],
sortname: "AuthorID",
sortorder: "desc",
viewrecords: true,
gridview: true,
width: 610,
height: 250,
caption: "Author List"
});
});
jQuery("#list").jqGrid("navGrid", "#pager", { edit: true, add: true, del: true });
yes , you can omit the 'cell' attribute and reduce your json data. you can also put 'id':0 which normally means treat the first item as the id. i also used 'key' attribute, but it's redundant. you can also pass your query result as Array too. if anyone can tell me is there any benefit of using List over others would much appreciated.
Thanks for your help
good luck

How to pass a parameter between two jQuery datatables

I have two datatables, one which lists foldes, and another which list's files within their parent folder. Here is how my script looks for the folder table:
var oTable = $('#folderTable').dataTable({
"bServerSide": true,
"sAjaxSource": "AJAXViewFolders",
"bProcessing": true,
"bFilter": false,
"aoColumns": [
{ "sName": "folder_id",
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj) {
return 'View';
}
},
{ "sName": "folder_name" },
{ "sName": "create_date" }
]
});
});
Now, when the user clicks the link I need to be able to pass that parentid to the file datatable. I have had no luck thus far. Here is how the JSON result looks in my controller, for the files datatable:
public JsonResult AJAXViewFiles(DataTableParamModel dtParams, int parentid)
{
var repo = new TrusteeDocumentRepository();
var allDocuments = repo.FindAllFiles().Where(c=>c.folder_id == parentid);
IEnumerable<Files> filteredFiles;
filteredFiles = allDocuments;
var displayedFiles = filteredFiles.Skip(dtParams.iDisplayStart).Take(dtParams.iDisplayLength);
var result = from c in displayedFiles select new[] { Convert.ToString(c.folder_id),c.file_name, c.upload_date.ToString() };
return Json(new
{
sEcho = dtParams.sEcho,
iTotalRecords = allDocuments.Count(),
iTotalDisplayRecords = filteredFiles.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
How would I go about getting the link in the folder table to pass the parentid to the jsonresult for the file's datatable successfully?
I assume the dataTables are on the same page so I'd switch it to a button...
"fnRender": function (oObj) {
return '<button type="button" class="folder-view" data-id="' + oObj.aData[0] + '">View</button>';
}
Add a live click handler so you can set the current parentid and refresh the files dataTable. Handler might look like this...
$('.folder-view').on('click', function() {
var $filesTable = $('#filesTable');
$filesTable.attr('data-parentid', $(this).attr('data-id'));
//refresh the files table
$filesTable.dataTable().fnDraw(false);
});
Finally, the files dataTable will need to override the fnServerData function to merge the extra parentid data...
"fnServerData": function (sSource, aoData, fnCallback) {
var extraData = [ { parentid: $('#filesTable').attr('data-parentid') } ];
$.ajax({
"dataType": "json",
"type": "POST",
"url": sSource,
"data": $.merge(extraData, aoData),
"success": fnCallback
});
}

Categories