DataTables in ASP.net using JSON - c#

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

Related

Jquery returns value "undefined" .net core

I want to populate second dropdown from first one.
It all works but city names and values just returns "undefined". *Number of cities returns correct but the name and value are always "undefined". *
Controller:
[HttpPost]
public ActionResult getCityJson(string stateId)
{
int _stateid = Convert.ToInt32(stateId);
List<Cities> objcity = new List<Cities>();
objcity = _db.Cities.Where(m => m.stateID == _stateid).ToList();
SelectList obgcity = new SelectList(objcity, "CityID", "CityName", 0);
return Json(obgcity);
}
View Page:
$("#istateid").change(function () {
var id = $("#istateid").val();
$.ajax({
url: '#Url.Action("getCityJson", "Home")',
data: { stateId: id },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#icityid").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
I also tried Public JsonResult and return JsonResult and Public Selectlist and return SelectList but none of them worked.
And I also tried this:
$("#istateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("getCityJson", "Home")',
data: { stateId: $("#istateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your City--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
}) });
I recieve this in browser:
(TypeError: data[x] is undefined.)
$("#istateid").change(function () {
var id = $("#istateid").val();
$.ajax({
url: '/Home/getCityJson',
data: { stateId: id },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++)
{ markup += "<option value=" + data[x].CityID + ">" + data[x].CityName + "</option>"; }
$("#icityid").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
<option value="0">Select City</option>
<option value="undefined">undefined</option>
<option value="undefined">undefined</option>
<option value="undefined">undefined</option>
Solved:
items.push("<option value=" + this.value + ">" + this.text + "</option>");
Value and text camel cased.
Special thanks to #agua from mars
Other codes I tried:
$("#istateid").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("getCityJson", "Admin")',
data: { stateId: $("#istateid > option:selected").attr("value") },
success: function (data) {
var items = [];
items.push("<option>--Choose Your Area--</option>");
$.each(data, function () {
items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$("#icityid").html(items.join(' '));
}
})
});
Controller:
[HttpPost]
public JsonResult getCityJson(string stateId, string selectCityId = null)
{
return Json(getCity(stateId, selectCityId));
}
public SelectList getCity(string stateId, string selectCityId = null)
{
IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(stateId))
{
int _stateId = Convert.ToInt32(stateId);
cityList = (from m in db.Cities where m.StateID == _stateId select m).AsEnumerable().Select(m => new SelectListItem() { Text = m.CityName, Value = m.CityID.ToString() });
}
return new SelectList(cityList, "Value", "Text", selectCityId);
}
try this:
success: function (data) {
var response=JSON.parse(data);
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < response.length; x++)
{ markup += "<option value=" + response[x].CityID + ">" + response[x].CityName + "</option>"; }
$("#icityid").html(markup).show();
},

Export to Excel directly from datasource with sorting and grouping for Kendo UI

I am trying to export data to excel file directly from datasource, I am able to export it to excel but the problem is the data are not sorted the way I want it to be nor group in the way I want it to be.
No matter what I do, the output is not sorted the way I want it to be, it is just as same as the way the data is retrieved from datasource.
Sample Input data:
|Celine|29|Female|
|Kian|25|Male|
|Juan|40|Male|
|Satia|25|Female|
|Kulim|50|Male|
|Liz|15|Female|
Sample Output in excel:
|Liz|15|Female|
|Satia|25|Female|
|Celine|29|Female|
|Kian|25|Male|
|Juan|40|Male|
|Kulim|50|Male|
Here is a snippet of code I used:
$(".export-excel").click(function () {
var from = new Date($("input#startDate").val()), to = new Date($("input#endDate").val());
var ds = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
url: webApiUrl +
"/data/getdata(startDateString='" +
(from.getFullYear() + "-" + (from.getMonth() + 1) + "-" + from.getDate()) +
"', endDateString='" + (to.getFullYear() + "-" + (to.getMonth() + 1) + "-" + to.getDate()) + "')",
dataType: "json"
},
parameterMap: function (options, data) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
var d = kendo.data.transports.odata.parameterMap(data);
delete paramMap.$inlinecount;
delete paramMap.$format;
paramMap.$count = true;
return paramMap;
}
},
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data['odata.count'];
},
errors: function (data) {
},
model: {
fields: {
Name: { type: "string" },
Age: { type: "string" },
Gender: {type:"string"}
}
},
group: {
field: "Gender"
}
},
sort: {
field: "Gender",
dir: "asc"
},
sortable: true,
pageable: true,
groupable: true,
filterable: true,
});
ds.fetch(function () {
var data = this.data();
for (var i = 0; i < data.length; i++) {
rows.push({
cells: [
{ value: data[i].Name },
{ value: data[i].Age},
{ value: data[i].Gender}
]
})
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: [
// Column settings (width)
{ autoWidth: true },
{ autoWidth: true },
{ autoWidth: true }
],
title: "Peaple_Report"
}
]
});
//save the file as Excel file with extension xlsx
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: "Test.xlsx" });
});
});
Thank you in advanced.
.data() method holds the pristine data when not sorted or filtered ...
when you have applied any filter or sorting or grouping or paging ... you should read the data from .view() method ... that will give you the sorted/filtered data you are looking for ...
here is the documentation of .view() method - http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#methods-view

Getting Null for .val()

I have inputs and selects. For some reason, some of them are giving me a null. Here is the code:
<script type="text/javascript">
$(function () {
$('#add').on('click', function () {
$('table').append('<tr>' +
'<td><button class=\'save\'>Save</button></td>' +
'<td><input name=\'name\' id=\'companyName\' /></td>' +
'<td><input name=\'currency\' id=\'currency\' /></td>' +
'<td><input name=\'ISOCode\' id=\'ISOCode\' /></td>' +
'<td><input name=\'CalcDeadLine\' id=\'CalcDeadLine\' /></td>' +
'<td><select name=\'mealAlgorithm\' id=\'mealAlgorithm\'><option value="True">Yes</option><option value="False">No</option></select></td>' +
'<td><input name=\'breakfast\' id=\'breakfast\' /></td>' +
'<td><input name=\'halfBoard\' id=\'halfBoard\' /></td>' +
'<td><input name=\'fullBoard\' id=\'fullBoard\' /></td>' +
'<td><input name=\'adminID\' id=\'adminID\' /></td>' +
'<td><input name=\'language\' id=\'language\' /></td>' +
'<td><input name=\'approvalcid\' id=\'cid\' /></td>' +
'<td><select name=\'useSMS\' id=\'useSMS\'><option value="True">Yes</option><option value="False">No</option></select></td>' +
'<td><select name=\'active\' id=\'active\'><option value="True">Yes</option><option value="False">No</option></select></td>');
$('#add').hide();
})
});
$(".save").live("click", function () {
var name = $("#companyName").val();
var currency = $("#currency").val();
var isoCode = $("#ISOCode").val();
var calcDeadLine = $("#CalcDeadLine").val();
var mealAlgorithm = $("#mealAlgorithm").val();
var noMeal = 111;
var breakfast = $("#breakfast").val();
var halfBoard = $("#halfBoard").val();
var fullBoard = $("#fullBoard").val();
var adminID = $("#adminID").val();
var language = $("#language").val();
var cid = $("#cid").val();
var useSms = $("#useSMS").val();
var active = $("#active").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("SaveCompany", "Admin")',
data: {
"CompanyName": name, "Currency": currency, "ISOCompanyCode": isoCode, "CalcDeadline": calcDeadLine,
"UseMealAlgorithm": mealAlgorithm, "NoMeal": noMeal, "Breakfast": breakfast, "HalfBoard": halfBoard,
"FullBoard": fullBoard, "AdminUserID": adminID, "ApprovalCulture": language, "ApprovalLcid": cid,
"UseSMS": useSms, "Active": active},
dataType: "json",
beforeSend: function () {
},
success: function (data) {
if (data.result == true) {
$("#GridCompany").html("Record has been saved!");
}
else {
alert("There is some error.");
}
}
})
})
In url of post everything is ok, it has true/false and every parameter with every value fulfilled.
In my controller I have
[HttpGet]
public JsonResult SaveCompany(string name, string currency, string isoCode, int calcDeadline, bool? mealAlgorithm,
int noMeal, int breakfast, int halfBoard, int fullBoard, string adminUserId, string approvalCulture,
int? approvalCid, bool? useSms, bool? active)
{
bool result = false;
try
{
result = _companyRepository.SaveCompany(name, currency, isoCode, calcDeadline, mealAlgorithm, noMeal,
breakfast, halfBoard, fullBoard, adminUserId, approvalCulture, approvalCid, useSms, active);
}
catch(Exception ex)
{
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
Nulls are isoCode, mealAlgorithm, approvalCid.
The problem is the wrong names of the fields.
In the AJAX you pass ISOCompanyCode but in the Action you're waiting for isoCode
The same is for the other two fields (you have different names). Use the same names and it'll fix your problem.

ColumnFiltering a DataTables tble using c# server side processing

Ok, I have a table which is populated using DataTables server side functionality. I have also added the .ColumnFilter plugin to search on individual columns. My problem is, is that the main global search works fine, but the individual one doesnt do anything.
The DataTables config is as such
var getUserNames = function () {
$("#tbl").dataTable({
"oLanguage": {
"sZeroRecords": "No records to display",
"sSearch": "Search on UserName"
},
"sDom": "<'row-fluid'<'span6'T><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
"oTableTools": {
"sSwfPath": "media/swf/copy_csv_xls_pdf.swf",
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": ["csv", "xls", "pdf"]
}
]
},
"aLengthMenu": [[25, 50, 100, 150, 250, 500, -1], [25, 50, 100, 150, 250, 500, "All"]],
"iDisplayLength": 20,
"bSortClasses": false,
"bStateSave": false,
"bPaginate": true,
"bAutoWidth": false,
"bProcessing": true,
"bServerSide": true,
"bDestroy": true,
"sAjaxSource": "WebService1.asmx/GetItems",
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bDeferRender": true,
"fnServerParams": function (aoData) {
aoData.push({ "name": "iParticipant", "value": $("#participant").val
(), "name": "iArchiveYears", "value": $("#ArchiveYears option:selected").text() });
},
"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);
$("#tbl").show();
}
});
}
})
.columnFilter({
aoColumns: [
{ type: "text" },
{ type: "text" }
]
});
}
with this as my Webservice:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Configuration;
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService {
public WebService1 () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string GetItems()
{
int sEcho = ToInt(HttpContext.Current.Request.Params["sEcho"]);
int iDisplayLength = ToInt(HttpContext.Current.Request.Params["iDisplayLength"]);
int iDisplayStart = ToInt(HttpContext.Current.Request.Params["iDisplayStart"]);
string rawSearch = HttpContext.Current.Request.Params["sSearch"];
string participant = HttpContext.Current.Request.Params["iParticipant"];
string archiveYears = HttpContext.Current.Request.Params["iArchiveYears"];
DateTime year = DateTime.Now;
if (archiveYears == null)
{
archiveYears = year.Year.ToString();
}
var sb = new StringBuilder();
var whereClause = string.Empty;
if (participant.Length > 0)
{
sb.Append(" Where participant = ");
sb.Append("'" + participant + "'");
sb.Append(" AND Year(MsgDate)= ");
sb.Append("'" + archiveYears + "'");
whereClause = sb.ToString();
}
sb.Clear();
var filteredWhere = string.Empty;
var wrappedSearch = "'%" + rawSearch + "%'";
if (rawSearch.Length > 0)
{
sb.Append(" WHERE Participant LIKE ");
sb.Append(wrappedSearch);
sb.Append(" OR MsgDate LIKE ");
sb.Append(wrappedSearch);
filteredWhere = sb.ToString();
}
//ORDERING
sb.Clear();
//Check which column is to be sorted by in which direction
for (int i = 0; i < 11; i++)
{
if (HttpContext.Current.Request.Params["bSortable_" + i] == "true")
{
sb.Append(HttpContext.Current.Request.Params["iSortCol_" + i]);
sb.Append(" ");
sb.Append(HttpContext.Current.Request.Params["sSortDir_" + i]);
}
}
orderByClause = sb.ToString();
if (!String.IsNullOrEmpty(orderByClause))
orderByClause = orderByClause.Replace("0", ", Participant ");
orderByClause = orderByClause.Replace("2", ", MsgDate ");
orderByClause = orderByClause.Remove(0, 1);
}
else
{
orderByClause = "MsgDate ASC";
}
orderByClause = "ORDER BY " + orderByClause;
sb.Clear();
var numberOfRowsToReturn = "";
numberOfRowsToReturn = iDisplayLength == -1 ? "TotalRows" : (iDisplayStart + iDisplayLength).ToString();
string query = #"
declare #MA TABLE( Participant VARCHAR(50), MsgDate DateTime))
INSERT
INTO
#MA ( Participant, MsgDate
FROM [MsgDateDetail]
{4}
SELECT *
FROM
(SELECT row_number() OVER ({0}) AS RowNumber
, *
FROM
(SELECT (SELECT count([#MA].Participant)
FROM
#MA) AS TotalRows
, ( SELECT count( [#MA].Participant) FROM #MA {1}) AS TotalDisplayRows
,[#MA].Participant
[#MA].MsgDate
FROM
#MA {1}) RawResults) Results
WHERE
RowNumber BETWEEN {2} AND {3}";
query = String.Format(query, orderByClause, filteredWhere, iDisplayStart + 1, numberOfRowsToReturn, whereClause);
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MIReporting"].ConnectionString);
try
{
conn.Open();
}
catch(Exception e )
{
Console.WriteLine(e.ToString());
}
var DB=new SqlCommand();
DB.Connection=conn;
DB.CommandText=query;
var data = DB.ExecuteReader();
var totalDisplayRecords = "";
var totalRecords = "";
string outputJson = string.Empty;
var rowClass = "";
var count = 0;
while(data.Read())
{
if (totalRecords.Length ==0)
{
totalRecords = data["TotalRows"].ToString();
totalDisplayRecords = data["TotalDisplayRows"].ToString();
}
sb.Append("{");
sb.AppendFormat(#"""DT_RowId"": ""{0}""", count++);
sb.Append(",");
sb.AppendFormat(#"""DT_RowClass"": ""{0}""", rowClass);
sb.Append(",");
sb.AppendFormat(#"""0"": ""{0}""", data["Participant"]);
sb.Append(",");
sb.AppendFormat(#"""2"": ""{0}""", data["MsgDate"]).Replace("\t", String.Empty);
sb.Append("},");
}
// handles zero records
if (totalRecords.Length == 0)
{
sb.Append("{");
sb.Append(#"""sEcho"": ");
sb.AppendFormat(#"""{0}""", sEcho);
sb.Append(",");
sb.Append(#"""iTotalRecords"": 0");
sb.Append(",");
sb.Append(#"""iTotalDisplayRecords"": 0");
sb.Append(", ");
sb.Append(#"""aaData"": [ ");
sb.Append("]}");
outputJson = sb.ToString();
return outputJson;
}
outputJson = sb.Remove(sb.Length - 1, 1).ToString();
sb.Clear();
sb.Append("{");
sb.Append(#"""sEcho"": ");
sb.AppendFormat(#"""{0}""", sEcho);
sb.Append(",");
sb.Append(#"""iTotalRecords"": ");
sb.Append(totalRecords);
sb.Append(",");
sb.Append(#"""iTotalDisplayRecords"": ");
sb.Append(totalDisplayRecords);
sb.Append(", ");
sb.Append(#"""aaData"": [ ");
sb.Append(outputJson);
sb.Append("]}");
outputJson = sb.ToString();
return outputJson;
}
public static int ToInt(string toParse)
{
int result;
if (int.TryParse(toParse, out result)) return result;
return result;
}
}
Now I see when I start to enter into one of the colFilter text boxes in FireBug, that the value are being stored in HttpContext.Current.Request.Params["sSearch_1"] but I'm not sure how I can apply this to the individual column and not a global search. I will also need to at a later point add the date-range to filter on the MsgDate col.
Any help would be appreciated.
columnFilter doesn't work very well. there is some bug...
i recommand another approach and it work well and more flexible.
you can create your own input like (example):
<input id="mysearchfiltercolumn1" type="text" />
in your datatable you can add this :
var table = $("#tbl").dataTable({
//[...]
"fnServerParams": function (aoData) {
aoData.push({ "name": "mycolumn1", "value": $('#mysearchfiltercolumn1').val() });
aoData.push({ "name": "mycolumn2", "value": $('#mysearchfiltercolumn2').val() });
aoData.push({ "name": "mycolumn3", "value": $('#mysearchfiltercolumn2').val() });
}
});
...and you bind your inputs like this :
$("#mysearchfiltercolumn1,#mysearchfiltercolumn2,#mysearchfiltercolumn3").bind('keyup',function (event) {
table.fnDraw();
});
and server-side you should see Request['mycolumn1'] and do make you want in order to give the result.
you can convert HttpContext.Current.Request.Params["sEcho"] by Request['sEcho'] etc...

sorting in asp.net

var store = new FMP.AspNetJsonStore({
fields: [
{ name: 'AssetID' },
{ name: 'AssociationID' },
{ name: 'Image' },
{ name: 'StatusName' },
{ name: 'ModelName' },
{ name: 'IPAddress' },
{ name: 'InScope', type: 'boolean' },
{ name: 'ServicePlanName' },
{ name: 'PricePlanName' },
{ name: 'PricePlanDescription' },
{ name: 'Program' },
{ name: 'ServicePlanID' },
{ name: 'Customer' },
{ name: 'Black', type: 'float' },
{ name: 'Cyan', type: 'float' },
{ name: 'Magenta', type: 'float' },
{ name: 'Yellow', type: 'float' },
{ name: 'BlackPct' },
{ name: 'CyanPct' },
{ name: 'MagentaPct' },
{ name: 'YellowPct' },
{ name: 'PrinterMarkerSupplies' },
{ name: 'PageCount' },
{ name: 'BlackImpressions' },
{ name: 'ColorImpressions' },
{ name: 'PricePlanID' },
{ name: 'ResponsibilityForAction' },
{ name: 'PrinterSerialNumber' }
],
totalProperty: "TotalCount",
autoLoad: { params: { start: 0, limit: myPageSize} },
//autoLoad: true,
proxy: new Ext.data.HttpProxy({
// Call web service method using GET syntax
url: 'GetPrintersGrid.asmx/buildGrid',
// Ask for Json response
headers: { 'Content-type': 'application/json' },
method: "GET"
}),
remoteSort: true,
//sortInfo: { field: 'PageCount', direction: "DESC" },
groupField: 'Customer',
root: 'Records'
});
store.setDefaultSort('PageCount', 'DESC');
Here is the web service i used
public PagedResult<FMPAsset> buildGrid(int start, int limit, string sortfield, string dir)
{
var a=5;
Guid AccountID = (Guid)Session["AccountID"];
//string sortdir;
//if( dir == "DESC")
//{
// sortdir = dir.Substring(0, 4).Trim().ToUpper();
//}
//else
//{
// sortdir = dir.Substring(0, 3).Trim().ToUpper();
//}
string SortExpression = sortfield + " " + (!String.IsNullOrEmpty(dir) ? dir : String.Empty);
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' order by a.PageCount = '" + + "'";
string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "' Order By a."+SortExpression;
//string whereClause = "SELECT value a , ROW_NUMBER() OVER(ORDER BY"
// + " " + SortExpression
// + ") As RowNumber FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'"
// + AccountID + "'";
//string whereClause = "SELECT value a FROM XSP_AssetList_V AS a WHERE a.AccountID = GUID'" + AccountID + "'";
List<FMPAsset> fmpAssets = new List<FMPAsset>();
using (XSPAssetModel.XSPAssetEntities assetEntities = new XSPAssetEntities(b.BuildEntityConnectionString1("XSMDSN")))
{
ObjectQuery<XSP_AssetList_V> assets = new ObjectQuery<XSP_AssetList_V>(whereClause, assetEntities);
//var assetOrder = assets.OrderBy(x => x.StatusName).ToList();
var assetPage = assets.Skip(start).Take(limit);
//var totalAssetCount = assets.Count();
currentAssets = assetPage.ToList();
int currentAssetsCount = currentAssets.Count;
string imgprefix = System.Configuration.ConfigurationManager.AppSettings["ImgPrefix"];
char[] separators = { '/' };
string appname = "";
int lastloc = imgprefix.Substring(0, imgprefix.Length - 1).LastIndexOfAny(separators);
if (lastloc > 6)
{
appname = imgprefix.Substring(lastloc + 1);
}
FMPAsset asset = new FMPAsset();
//StreamWriter sw = new StreamWriter("C:\\test.txt");
XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities markerCtx =
new XSPPrinterMarkerSupplyModel.XSPPrinterMarkerSupplyEntities(b.BuildEntityConnectionString1("XSMDSN"));
for (int x = 0; x < currentAssetsCount; x++)
{
asset = new FMPAsset();
asset.AssetID = currentAssets[x].AssetID.ToString();
asset.PricePlanID = currentAssets[x].PricePlanID.ToString();
asset.AssociationID = currentAssets[x].AssociationID;
asset.ModelName = currentAssets[x].ModelName;
asset.ResponsibilityForAction = currentAssets[x].ResponsibilityForAction;
asset.IPAddress = (String.IsNullOrEmpty(currentAssets[x].PrinterIPAddress)) ? "No IP" : currentAssets[x].PrinterIPAddress; ;
if (currentAssets[x].InScope)
{
asset.InScope = b.GetString("SDE_YES");
}
else
{
asset.InScope = b.GetString("SDE_NO");
}
asset = SetStatus(appname, asset, x);
asset.PricePlanName = currentAssets[x].Program;
asset.PricePlanDescription = currentAssets[x].PricePlanDescription;
asset.ServicePlanName = currentAssets[x].ServicePlanName;
if (currentAssets[x].PrinterSerialNumber != null)
{
asset.PrinterSerialNumber = currentAssets[x].PrinterSerialNumber;
}
else
{
asset.PrinterSerialNumber = "-";
}
//sw.WriteLine("ChargebackDescription: " + DateTime.Now.Millisecond);
if (this.b.UseChargebackDescription
&& !String.IsNullOrEmpty(currentAssets[x].CustomerChargebackDescription)
&& currentAssets[x].CustomerChargebackDescription != "Generated by OUT Integration")
{
asset.Customer = currentAssets[x].CustomerChargebackDescription;
if (asset.Customer.IndexOf(Environment.NewLine) > -1)
{
asset.Customer =
asset.Customer.Substring(0, asset.Customer.IndexOf(Environment.NewLine));
}
}
else
{
asset.Customer = currentAssets[x].CustomerChargeBackEntryName;
}
if (this.b.UsePricePlanDescription && !String.IsNullOrEmpty(currentAssets[x].PricePlanDescription))
{
asset.Program = currentAssets[x].PricePlanDescription;
if (asset.Program.IndexOf(Environment.NewLine) > -1)
{
asset.Program =
asset.Program.Substring(0, asset.Program.IndexOf(Environment.NewLine));
}
}
else
{
asset.Program = currentAssets[x].Program;
}
asset.BlackPct = -3;
asset.CyanPct = -3;
asset.MagentaPct = -3;
asset.YellowPct = -3;
Guid id = currentAssets[x].AssetID;
asset = SetCMYKvalues(asset, x);
BuilldImpressionsValues(currentAssets[x], ref asset);
fmpAssets.Add(asset);
}
//CommonGrid1.ApplyUserPreferences();
//JavaScriptSerializer json = new JavaScriptSerializer();
//string JsonArray = json.Serialize(fmpAssets);
//string ArrayDeclaration = string.Format("var arr = {0};", JsonArray);
//Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "fmpAssets", ArrayDeclaration, true);
//assetEntities.Dispose();
var totalAssetCount = assets.Count();
var y = new PagedResult<FMPAsset>();
y.Records = fmpAssets;
y.TotalCount = totalAssetCount;
return y;
// CommonGrid1.BindDataSource(SortByStatusName(fmpAssets));
}
}
I am getting an error saying:
{"Message":"Invalid JSON primitive:
DESC.","StackTrace":" at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n
at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32
depth)\r\n at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String
input, Int32 depthLimit,
JavaScriptSerializer serializer)\r\n
at
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer
serializer, String input, Type type,
Int32 depthLimit)\r\n at
System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext
context, JavaScriptSerializer
serializer, WebServiceMethodData
methodData)\r\n at
System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData
methodData, HttpContext context)\r\n
at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
context, WebServiceMethodData
methodData)","ExceptionType":"System.ArgumentException"}
Can anyone help me in this issue?
Sure Here is the JSON store
Ext.ns("FMP");
FMP.AspNetJsonReader = Ext.extend(Ext.data.JsonReader, {
read: function(response) {
// Assuming ASP.NET encoding - Data is stored as
var json = response.responseText;
var o = Ext.decode(json);
if (!o) {
throw { message: "AspNetJsonReader.read: Json object not found" };
}
if (!o.d) {
throw { message: "AspNetJsonReader.read: Root element d not found" };
}
return this.readRecords(o.d);
}
});
FMP.AspNetJsonStore = Ext.extend(Ext.data.GroupingStore, {
/**
* #cfg {Ext.data.DataReader} reader #hide
*/
constructor: function(config) {
FMP.AspNetJsonStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new FMP.AspNetJsonReader(config)
}));
}
});

Categories

Resources