jQuery Datatable is not displaying Date data in the datable column - c#

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.

Related

Jquery DataTable client side pagination, searching, filtering along with a server side data using Version 1.10.24

Dear Fellows i am unable to find the example of Jquery datatable with clientside pagination, sorting and searching while using a server side data please suggest the solution to me mean while i am attaching sample code till now that what i have done already using server side filtering pagination and searching that searching is not going good as in example available in jquery datatable site.
--JsFile contains code
$(document).ready(function () {
$("#DomainDatatable").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"pageLength": 10,
"deferRender": true,
"scrollY": 500,
"scrollCollapse": true,
"scroller": true,
"ajax": {
"url": "/Domain/GetDomainData",
"type": "POST",
"datatype": "json"
},
"columnDefs": [{
"targets": [0],
"visible": false,
"searchable": false
},
{
"targets": [1],
"searchable": true,
},
{
"targets": [2],
"orderable": true
},
{
"targets": [3],
"searchable": true,
"orderable": false
},
{
"targets": [4],
"searchable": true,
"orderable": false
},
],
"columns": [
{ "data": "id", "name": "Id", "autoWidth": true },
{ "data": "domainName", "name": "DomainName", "autoWidth": true, "searchable": true },
{
data: "createdOn", "name": "CreatedOn", "autoWidth": true,
"render": function (value) {
if (value === null) return "";
return moment(value).format('D-MMM-YYYY hh:mm');
}
},
{ "data": "isActive", "name": "IsActive", "autoWidth": true },
{ "data": "createdByName", "name": "CreatedByName", "autoWidth": true },
{
data: "updatedOn", "name": "UpdatedOn", "autoWidth": true,
"render": function (value) {
if (value === null) return "";
return moment(value).format('D-MMM-YYYY hh:mm');
}
},
{ "data": "updatedByName", "name": "UpdatedByName", "autoWidth": true },
{
"render": function (data, type, full, meta) {
return (
"<button class='btn btn-default btn-xs' style='display:flex;flex-flow:rownowrap;justify-content:center;' onClick='EditForm(" + full.id + ",\"" + full.domainName + "\",\"" + full.isActive + "\" );'>" + "Edit" + "</button>"
);
}
},
]
});
});
Controller Contains
public async Task<JsonResult> GetData()
{
try
{
var draw = Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
var sortColumnDir = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault();
//Paging Size (10,20,50,100)
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
//All User Data
var domain_data = await _iUnitOfWork.DomainRepository.GetData();
//Sorting
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
domain_data = domain_data.AsQueryable().OrderBy(sortColumn + " " + sortColumnDir);
}
//Search
if (!string.IsNullOrEmpty(searchValue))
{
domain_data = domain_data.Where(m => m.DomainName == searchValue
|| m.CreatedByName == searchValue || m.IsActive == searchValue);
}
//total number of rows count
recordsTotal = domain_data.Count();
//Paging
var data = domain_data.Skip(skip).Take(pageSize).ToList();
//Returning Json Data
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data });
}
catch (Exception ex)
{
throw ex;
}
}
Repository Contains
public async Task<IEnumerable<M.DomainModel>> GetData()
{
try
{
var ur = await DataContext.appUsers.ToListAsync();
IEnumerable<M.DomainModel> result = await DataContext.domains.Include(a=>a.FKCreatedBy).Include(a=>a.FkUpdatedBy).Select(x => new M.DomainModel()
{
Id = x.Id,
DomainName = x.Name,
IsActive = x.IsActive == true ? "Yes" : "No",
CreatedOn = x.CreatedOn,
FkCreatedById = x.FKCreatedById,
CreatedByName = x.FKCreatedBy.UserName,
UpdatedOn = x.UpdatedOn,
FKUpdatedById = x.FKUpdatedById,
UpdatedByName = x.FkUpdatedBy == null ? "" : x.FkUpdatedBy.UserName,
}).ToListAsync();
return result;
}
catch (Exception ex)
{
throw ex;
}
}

How to fix this issue, System.Linq.Dynamic.ParseException: No property or field asc exist in type 'TblEventsManagements'?

enter image description hereI have this controller GetList and i am using Linq.Dynamic to filter for fields in the table be searched and this uses dataTable for server side processing. Who can help me to resolve this problem? Below is my logic and line where this error is thrown;
[\[HttpPost\]
public ActionResult GetList()
{
//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\]"\];
using (eNtsaOnlineRegistrationDBContext db = new eNtsaOnlineRegistrationDBContext())
{
IQueryable<TblEventsManagements> empList = db.TblEventsManagements;
int totalrows = empList.Count();
int totalrowsafterfiltering = totalrows;
if (!string.IsNullOrEmpty(searchValue))
{
empList = empList.Where(x => x.TrainingType.Contains(searchValue) || x.TrainingDescription.Contains(searchValue) || x.Price.ToString().Contains(searchValue.ToLower())
|| x.Venue.Contains(searchValue) || x.Facilitator.Contains(searchValue) || x.WhoAttend.Contains(searchValue) || x.Rsvp.Contains(searchValue));
}
empList = empList.OrderBy(sortColumnName + "" + sortDirection).Skip(start).Take(length);
return Json(new { data = empList, draw = Request\["draw"\], recordsTotal = totalrows, recordsFiltered = totalrowsafterfiltering }, JsonRequestBehavior.AllowGet);
}
}][1]
I forgot to put my Ajax call, i thought at first the issue was missing field from my table. Now i am getting field or type 'TrainingTypeasc' is not exist, well it does on my table from the database. Where can i improve this logic mates? Please help.
<script>
$(document).ready(function () {
$("#EventManagementTable").DataTable({
"ajax": {
"url": "/Dashboard/GetList",
"type": "POST",
"datatype":"json"
},
"columns": [
{"data": "TrainingType", "name": "TrainingType"},
{ "data": "TrainingDescription", "name": "TrainingDescription" },
{ "data": "Price", "name": "Price" },
{ "data": "Venue", "name": "Venue" },
{ "data": "Facilitator", "name": "Facilitator" },
{ "data": "WhoAttend", "name": "WhoAttend" },
{"data": "RSVP", "name": "RSVP"},
],
"serverSide": "true",
"order":[0,"asc"],
"processing": "true",
"language": {
"processing":"processing... please wait"
}
});
});
Replace this :
empList = empList.OrderBy(sortColumnName + "" + sortDirection).Skip(start).Take(length);
with this:
empList = empList.OrderByPropertyName(sortColumnName,sortDirection).Skip(start).Take(length)
and add this to your project:
using System.Collections.Generic;
using System.Linq;
namespace "YourNameSpace"
{
public static class ListExtension
{
public static IOrderedEnumerable<T> OrderByPropertyName<T>(this ICollection<T> list, string sortColumnName, string sortDirection)
{
var type = typeof(T);
var property = sortColumnName == "" ? type.GetProperties().FirstOrDefault() : type.GetProperties().Where(p => p.Name == sortColumnName).FirstOrDefault();
return sortColumnName == "asc" ? list.OrderBy(p => property.GetValue(p)) : list.OrderByDescending(p => property.GetValue(p));
}
}
}

Datatable server side processing c# mvc

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.

DataTables in ASP.net using JSON

Using JQuery DataTables in ASP.net and trying to return JSON data to it from C# WebMethod.
C# method...
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Data()
{
string json = string.Empty;
using (IDataReader reader = DBUtil.GetReader("data", "data", "pram"))
{
if (reader != null)
{
DataTable dt = new DataTable();
dt.Load(reader);
reader.Close();
json = JsonHelper.GetJsonFromDataTable(dt);
}
}
return json; //also tried by adding "{\"aaData\": " + json + "}"
}
Working....
var source = {};
$.ajax({
type: 'POST',
dataType: 'json',
url: "page.aspx/Data",
contentType: 'application/json; charset=utf-8',
cache: false,
data: {},
success: function (response) {
source = $.parseJSON(response.d);
alert(response.d); // i can see Json formatted data
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
}
});
Not working....... (not even hitting the method break point)
$(".JGrid").dataTable({
"bJQueryUI": true,
"sAjaxSource": "../page.aspx/Data", //also tried with var 'source' (declared sbove)
"aoColumns": [
{ "sTitle": "Col1name", "sWidth": "33%" },
{ "sTitle": "Col2name", "sWidth": "33%" },
{ "sTitle": "Col3name", "sWidth": "33%" }
]
});
$("#table-tripNote").dataTable({
"oLanguage": {
"sZeroRecords": "No records to display",
"sSearch": "Search from all Records"
},
"bProcessing": true,
"bServerSide": true,
"bDestroy": true,
"sAjaxSource": "frmTrip.aspx/GetMemberNotesByTrip",
"sPaginationType": "full_numbers",
"bDeferRender": true,
"aoColumns":
[
null,
null,
null,
null,
null,
null,
null
],
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success":
function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#table-tripNote").show();
}
});
}
});
This was working for me
Check it out
Hello Brother add this property to your datatable
----"bServerSide": true,
like this
$(".JGrid").dataTable({
"bJQueryUI": true,
"bServerSide": true,
"sAjaxSource": "/page.aspx/Data", //also tried with var 'source' (declared sbove)
"aoColumns": [
{ "sTitle": "Col1name", "sWidth": "33%" },
{ "sTitle": "Col2name", "sWidth": "33%" },
{ "sTitle": "Col3name", "sWidth": "33%" }
]
});
Check out this page. Look at the "Parameters sent to the server". I think dataTables is expecting your server-side webmethod to accept these values. You can override what it sends I think by using the fnServerData (on the same page) option. This is called before data is sent to the back-end so you can have control over what is getting sent.
This post maybe useful.
[WebMethod()]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string GetMemberNotesByTrip(string sEcho, int iDisplayStart, int iDisplayLength)
{
string rawSearch = HttpContext.Current.Request.Params["sSearch"].Trim();
var whereClause = string.Empty;
var filteredWhere = "1=1";
var wrappedSearch = rawSearch.Trim();
var Tempsb = new StringBuilder();
Tempsb.Append("mbrid=" + MemberID);
if (TripID != 0)
{
Tempsb.Append("and trpid=" + TripID);
}
else
Tempsb.Append("and trpid=0");
if (rawSearch.Length > 0)
{
Tempsb.Append("AND ( ISNULL(trpDate,'''') LIKE ");
Tempsb.Append("'%" + wrappedSearch + "%'");
Tempsb.Append(" OR clrFullName LIKE ");
Tempsb.Append("'%" + wrappedSearch + "%'");
Tempsb.Append(" OR clrPhone LIKE ");
Tempsb.Append("'%" + wrappedSearch + "%'");
Tempsb.Append(" OR clrRelationshipToMember LIKE ");
Tempsb.Append("'%" + wrappedSearch + "%'");
Tempsb.Append(" OR trpNote LIKE ");
Tempsb.Append("'%" + wrappedSearch + "%'");
Tempsb.Append(" OR clrOrganization LIKE ");
Tempsb.Append("'%" + wrappedSearch + "%'");
Tempsb.Append(" OR trpIsGrievance LIKE ");
Tempsb.Append("'%" + wrappedSearch + "%'");
Tempsb.Append(")");
}
if (Tempsb.Length > 0)
filteredWhere = Tempsb.ToString();
string orderByClause = string.Empty;
orderByClause = "trpDate desc";
StringBuilder sb = new StringBuilder();
sb.Append(Convert.ToInt32(HttpContext.Current.Request.Params["iSortCol_0"]));
sb.Append(" ");
sb.Append(HttpContext.Current.Request.Params["sSortDir_0"]);
orderByClause = sb.ToString();
if (!String.IsNullOrEmpty(orderByClause))
{
orderByClause = orderByClause.Replace("0", ", trpDate ");
orderByClause = orderByClause.Replace("1", ", clrFullName ");
orderByClause = orderByClause.Replace("2", ", clrPhone ");
orderByClause = orderByClause.Replace("3", ", clrRelationshipToMember ");
orderByClause = orderByClause.Replace("4", ", clrOrganization ");
orderByClause = orderByClause.Replace("5", ", trpIsGrievance ");
orderByClause = orderByClause.Replace("6", ", trpNote ");
orderByClause = orderByClause.Remove(0, 1);
}
else
{
orderByClause = "pronID ASC";
}
DataSet ds = clsTrip.GetTripNotesMaster(filteredWhere, orderByClause, iDisplayLength, iDisplayStart, true);
List<clsTrip> lstTripNotesGrv = new List<clsTrip>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
clsTrip lsttripNotes = new clsTrip();
lsttripNotes.clrFullName = ds.Tables[0].Rows[i]["clrFullName"].ToString();
if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i]["trpDate"].ToString()))
lsttripNotes.trpDate = Convert.ToDateTime(ds.Tables[0].Rows[i]["trpDate"].ToString());
else
lsttripNotes.trpDate = DateTime.MinValue;
lsttripNotes.clrPhone = ds.Tables[0].Rows[i]["clrPhone"].ToString();
lsttripNotes.clrRelationshipToMember = ds.Tables[0].Rows[i]["clrRelationshipToMember"].ToString();
lsttripNotes.clrOrganization = ds.Tables[0].Rows[i]["clrOrganization"].ToString();
if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i]["trpIsGrievance"].ToString()))
lsttripNotes.trpIsGrievance = Convert.ToBoolean(ds.Tables[0].Rows[i]["trpIsGrievance"].ToString());
else
lsttripNotes.trpIsGrievance = false;
lsttripNotes.trpNote = (ds.Tables[0].Rows[i]["trpNote"].ToString());
lstTripNotesGrv.Add(lsttripNotes);
}
int TotalRec = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
var result = from c in lstTripNotesGrv
select new[] {
//Convert.ToString(c.pronID),
c.trpDate !=null && c.trpDate!=DateTime.MinValue ? string.Format("{0:MMM d, yyyy}",c.trpDate):"-",
c.clrFullName.ToString(),
c.clrPhone.ToString(),
c.clrRelationshipToMember.ToString(),
c.clrOrganization.ToString(),
( Convert.ToBoolean(c.trpIsGrievance)?"Yes":"No"),
c.trpNote
};
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(new
{
sEcho,
iTotalRecords = TotalRec,
iTotalDisplayRecords = TotalRec,
aaData = result
});
}

jQuery DataTable JSON Parsing Error

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

Categories

Resources