Use jqgrid action formatter - asp.net

I fill grid by ashx file and its work fine.
When i add action in grid ,data of cell shift to right and last column show Null.
Before add Action
After add Action
grid in firebug:
ashx:
public void ProcessRequest(HttpContext context) {
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string _search = request["_search"];
string numberOfRows = request["rows"];
string pageIndex = request["page"];
string sortColumnName = request["sidx"];
string sortOrderBy = request["sord"];
int totalRecords;
Collection<User> users = GetDummyUsers(numberOfRows, pageIndex, sortColumnName, sortOrderBy, out totalRecords);
string output = BuildJQGridResults (users, Convert.ToInt32 (numberOfRows), Convert.ToInt32 (pageIndex), Convert.ToInt32 (totalRecords));
response.Write (output);
}
Create Users:
private Collection<User> GetDummyUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords) {
var data = new Collection<User> {
new User(){ UserID = 1,UserName = "Bill Gates", FirstName = "Bill", LastName = "Gates",EmailID = "test#microsoft.com", },
new User(){ UserID = 1,UserName = "Bill Gates", FirstName = "Bill", LastName = "Gates",EmailID = "test#microsoft.com", },
new User(){ UserID = 1,UserName = "Bill Gates", FirstName = "Bill", LastName = "Gates",EmailID = "test#microsoft.com", },
};
totalRecords = data.Count;
return data;
}
ConvetTo json:
private string BuildJQGridResults(Collection<User> users, int numberOfRows, int pageIndex, int totalRecords) {
JQGridResults result = new JQGridResults ();
List<JQGridRow> rows = new List<JQGridRow> ();
foreach (User user in users) {
JQGridRow row = new JQGridRow ();
row.id = user.UserID;
row.cell = new string[5];
row.cell[0] = user.UserID.ToString ();
row.cell[1] = user.UserName;
row.cell[2] = user.FirstName;
row.cell[3] = user.LastName;
row.cell[4] = user.EmailID;
rows.Add (row);
}
result.rows = rows.ToArray ();
result.page = pageIndex;
result.total = (totalRecords + numberOfRows - 1) / numberOfRows;
result.records = totalRecords;
return new JavaScriptSerializer ().Serialize (result);
}
grid:
url: 'jqGridHandler.ashx',
datatype: 'json',
autowidth: true,
height: 100,
colNames: ['ACTION', 'ID', 'UserName', 'FirstName', 'LastName', 'EmailID'],
colModel: [
{
name: 'act', width: 100, align: 'center', sortable: false, formatter: 'actions',
formatoptions: {
keys: true,
delOptions: true,
delbutton:true,
editbutton:false
}
},
{ name: 'UserID', width: 100, sortable: true, },
{ name: 'UserName', width: 100, sortable: true },
{ name: 'FirstName', width: 100, sortable: true },
{ name: 'LastName', width: 100, sortable: true },
{ name: 'EmailID', width: 100, sortable: true },
],
rowNum: 20,
loadonce: true,
rowList: [5, 10, 20],
recordpos: "left",
ignoreCase: true,
toppager: true,
viewrecords: true,
sortorder: "desc",
scrollOffset: 1,
});
});

jqGrid is treating actions as real column and it expects data for it. The easiest way out of this is to add empty cell to your row on server side:
private string BuildJQGridResults(Collection<User> users, int numberOfRows, int pageIndex, int totalRecords) {
JQGridResults result = new JQGridResults ();
List<JQGridRow> rows = new List<JQGridRow> ();
foreach (User user in users) {
JQGridRow row = new JQGridRow ();
row.id = user.UserID;
row.cell = new string[6];
row.cell[0] = String.Empty;
row.cell[1] = user.UserID.ToString ();
row.cell[2] = user.UserName;
row.cell[3] = user.FirstName;
row.cell[4] = user.LastName;
row.cell[5] = user.EmailID;
rows.Add (row);
}
result.rows = rows.ToArray ();
result.page = pageIndex;
result.total = (totalRecords + numberOfRows - 1) / numberOfRows;
result.records = totalRecords;
return new JavaScriptSerializer ().Serialize (result);
}
As an alternative you can use jqGrid in repeatItems: false mode. First you need to change the jqGrid initialization script:
$("#UsersGrid").jqGrid({
url: 'jqGridHandler.ashx',
datatype: 'json',
autowidth: true,
height: 100,
colNames: ['ACTION', 'ID', 'UserName', 'FirstName', 'LastName', 'EmailID'],
colModel: [
{ name: 'act', width: 100, align: 'center', sortable: false, formatter: 'actions', formatoptions: { keys: true, delOptions: true, delbutton:true, editbutton:false } },
{ name: 'UserID', width: 100, sortable: true, },
{ name: 'UserName', width: 100, sortable: true },
{ name: 'FirstName', width: 100, sortable: true },
{ name: 'LastName', width: 100, sortable: true },
{ name: 'EmailID', width: 100, sortable: true },
],
rowNum: 20,
loadonce: true,
rowList: [5, 10, 20],
recordpos: 'left',
ignoreCase: true,
toppager: true,
viewrecords: true,
sortorder: 'desc',
scrollOffset: 1,
jsonReader : {
repeatitems: false
}
});
Now on server side you can no longer use array, you have to use object or dictionary. I will show the more generic approach which is dictionary. Assuming your solution is based on this sample, you will have to change JQGridResult class like this:
public class JQGridResults
{
public int page;
public int total;
public int records;
public List<Dictionary<string, string>> rows;
}
Now your method can look like this:
private string BuildJQGridResults(Collection<User> users, int numberOfRows, int pageIndex, int totalRecords) {
JQGridResults result = new JQGridResults();
result.rows = new List<Dictionary<string, string>>();
foreach (User user in users) {
Dictionary<string, string> row = new Dictionary<string, string>();
row.Add("id", user.UserID.ToString());
row.Add("UserID", user.UserID.ToString());
row.Add("UserName", user.UserName);
row.Add("FirstName", user.FirstName);
row.Add("LastName", user.LastName);
row.Add("EmailID", user.EmailID);
result.rows.Add(row);
}
result.page = pageIndex;
result.total = (totalRecords + numberOfRows - 1) / numberOfRows;
result.records = totalRecords;
return new JavaScriptSerializer().Serialize(result);
}
This can be further optimized to avoid sending UserId twice, but this is not what is important from your question point of view.

Code works completely fine in my browser. Try with this code. Hopw it works also just check in your webdeveloper tools are you getting any error there.
Also paste your code for myDelOptions.
$("#datagrid").jqGrid({
url: 'jqGridHandler.ashx',
datatype: 'json',
autowidth: true,
height: 100,
colNames: [ 'ACTION', 'EOSysNum', 'PctIndNum', 'PctLettSubject', 'PctAssignSubject', ],
colModel: [
{
name: 'act', width: 100, align: 'center', sortable: false, formatter: 'actions',
formatoptions: {
keys: true,
delOptions: true,
delbutton:true,
editbutton:false
}
},
{ name: 'EOSysNum', index: 'UserID', width: 50, sortable: true, hidden: false },
{ name: 'PctIndNum', width: 140, sortable: true },
{ name: 'PctLettSubject', width: 140, sortable: true },
{ name: 'PctAssignSubject', width: 100, sortable: true },
],
rowNum: 20,
loadonce: true,
rowList: [5, 10, 20],
recordpos: "left",
ignoreCase: true,
toppager: true,
viewrecords: true,
sortorder: "desc",
scrollOffset: 1,
});

remove direction option from jqgrid and let us know it works or not

Related

nswag.json to flattenInheritanceHierarchy is not working dotnet 6

I'm trying to generate flate type script class using nswag
I belive there's a proprty 'flattenInheritanceHierarchy' that can do what i need. but seems like its not working. not sure what i'm missing.
I have a c# class called Result which is inheriting from Result
public partial record Result
{
public bool IsSucceeded { get; set; }
public string Message { get; set; } = string.Empty;
}
public partial record Result<T> : Result where T : new()
{
public T Value { get; set; } = new T();
}
i'm using it to retunr the result like this
public async Task<IActionResult> Create(CarDto dto)
{
return Ok(new Result<CarDto>());
}
when i generate typescript classes, actual result is
export class Result {
isSucceeded!: boolean;
message!: string;
}
export class ResultOfCarDto extends Result {
value!: CarDto;
}
but i want it like
export class ResultOfCarDto {
isSucceeded!: boolean;
message!: string;
value!: CarDto;
}
here's my nswag.json
{
"runtime": "Net60",
"defaultVariables": null,
"documentGenerator": {
"aspNetCoreToOpenApi": {
"project": "Web.csproj",
"msBuildProjectExtensionsPath": null,
"configuration": null,
"runtime": null,
"targetFramework": null,
"noBuild": true,
"verbose": false,
"workingDirectory": null,
"requireParametersWithoutDefault": true,
"apiGroupNames": null,
"defaultPropertyNameHandling": "CamelCase",
"defaultReferenceTypeNullHandling": "Null",
"defaultDictionaryValueReferenceTypeNullHandling": "NotNull",
"defaultResponseReferenceTypeNullHandling": "NotNull",
"defaultEnumHandling": "Integer",
"flattenInheritanceHierarchy": true,
"generateKnownTypes": true,
"generateEnumMappingDescription": true,
"generateXmlObjects": false,
"generateAbstractProperties": false,
"generateAbstractSchemas": true,
"ignoreObsoleteProperties": true,
"allowReferencesWithProperties": false,
"excludedTypeNames": [],
"serviceHost": null,
"serviceBasePath": null,
"serviceSchemes": [],
"infoTitle": "API",
"infoDescription": null,
"infoVersion": "1.0.0",
"documentTemplate": null,
"documentProcessorTypes": [],
"operationProcessorTypes": [],
"typeNameGeneratorType": null,
"schemaNameGeneratorType": null,
"contractResolverType": null,
"serializerSettingsType": null,
"useDocumentProvider": true,
"documentName": "v1",
"aspNetCoreEnvironment": null,
"createWebHostBuilderMethod": null,
"startupType": null,
"allowNullableBodyParameters": false,
"output": "wwwroot/api/specification.json",
"outputType": "OpenApi3",
"assemblyPaths": [],
"assemblyConfig": null,
"referencePaths": [],
"useNuGetCache": false
}
},
"codeGenerators": {
"openApiToTypeScriptClient": {
"className": "{controller}Client",
"moduleName": "",
"namespace": "",
"typeScriptVersion": 4.3,
"template": "Angular",
"promiseType": "Promise",
"httpClass": "HttpClient",
"withCredentials": false,
"useSingletonProvider": true,
"injectionTokenType": "InjectionToken",
"rxJsVersion": 6.0,
"dateTimeType": "Date",
"nullValue": "Undefined",
"generateClientClasses": false,
"generateClientInterfaces": false,
"generateOptionalParameters": false,
"exportTypes": true,
"wrapDtoExceptions": false,
"exceptionClass": "SwaggerException",
"clientBaseClass": null,
"wrapResponses": false,
"wrapResponseMethods": [],
"generateResponseClasses": true,
"responseClass": "SwaggerResponse",
"protectedMethods": [],
"configurationClass": null,
"useTransformOptionsMethod": false,
"useTransformResultMethod": false,
"flattenInheritanceHierarchy": false,
"generateDtoTypes": true,
"operationGenerationMode": "MultipleClientsFromOperationId",
"markOptionalProperties": false,
"generateCloneMethod": false,
"typeStyle": "Class",
"enumStyle": "Enum",
"useLeafType": true,
"classTypes": [],
"extendedClasses": [],
"extensionCode": null,
"generateDefaultValues": true,
"generateAbstractProperties": false,
"generateAbstractSchemas": false,
"ignoreObsoleteProperties": true,
"excludedTypeNames": [],
"excludedParameterNames": [],
"includeHttpContext": false,
"handleReferences": false,
"generateTypeCheckFunctions": false,
"generateConstructorInterface": false,
"convertConstructorInterfaceData": false,
"importRequiredTypes": true,
"useGetBaseUrlMethod": false,
"baseUrlTokenName": "API_BASE_URL",
"queryNullValue": "",
"inlineNamedDictionaries": false,
"inlineNamedAny": false,
"templateDirectory": null,
"typeNameGeneratorType": null,
"propertyNameGeneratorType": null,
"enumNameGeneratorType": null,
"serviceHost": null,
"serviceSchemes": null,
"output": "ClientApp/src/app/dto/api-dtos.ts"
}
}
}
addtionally its generating 3 fromJS, init and toJSON functions which i also dont want
export class StatusCountDto {
count!: number;
status!: string;
#region I dont want to generate this
init(_data?: any) {
if (_data) {
this.count = _data["count"];
this.status = _data["status"];
}
}
static fromJS(data: any): IssueCountDto {
data = typeof data === 'object' ? data : {};
let result = new IssueCountDto();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["count"] = this.count;
data["status"] = this.status;
return data;
}
#endregion I dont want to generate this
}
any suggesstion?

Muti-bar column Chart with Legend from Datatable

I am trying to plot a mutibar column chart with legend. This is my code. The code is seems to be working but its not adding legend in an appropriate format. I'm adding screenshots of my data table and the output coming from my code. The legend should be showing Different types of priorities but its showing "Legend Text" everywhere.
Output
Datatable
//Plotting Matrix Chart
chartMatrix.Visible = true;
LoadChartData(dtHourvsPriorityMatrix);
chartMatrix.Series["Priority"].ChartType = SeriesChartType.Column;
chartMatrix.Series["Priority"]["DrawingStyle"] = "Emboss";
//chartMatrix.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
chartMatrix.Series["Priority"].IsValueShownAsLabel = true;
// Create a new legend called "Legend".
chartMatrix.Legends.Add(new Legend("Legend"));
// Set Docking of the Legend chart to the Default Chart Area.
chartMatrix.Legends["Legend"].DockedToChartArea = "ChartAreaF";
// Assign the legend to Series=Priority.
chartMatrix.Series["Priority"].Legend = "Legend";
chartMatrix.Series["Priority"].IsVisibleInLegend = true;
LegendCellColumn lcc = new LegendCellColumn("Priority", LegendCellColumnType.Text, "LEGENDTEXT");
lcc.HeaderFont = new System.Drawing.Font("Trebuchet MS", 12F, System.Drawing.FontStyle.Bold);
chartMatrix.Legends["Legend"].CellColumns.Add(lcc);
private void LoadChartData(DataTable initialDataSource)
{
for (int i = 1; i < initialDataSource.Columns.Count; i++)
{
Series series = new Series();
foreach (DataRow dr in initialDataSource.Rows)
{
int y = (int)dr[i];
series.Points.AddXY(dr["Hour"].ToString(), y);
}
chartMatrix.Series.Add(series);
}
}
Try to use canvasjs chart.
Use web service for binding data
<script type="text/javascript">
$(document).ready(function () {
var district = $('#ContentPlaceHolder1_hiddistrict').val();
var assembly = $('#ContentPlaceHolder1_hidassembly').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "../WebMyVoterService.asmx/GenderWise",
data: '{"districtid":"' + district + '","assembly" :"' + assembly + '" }',
processData: false,
success: OnSuccess,
failure: function (response) {
alert(response);
},
error: function (response) {
alert(response);
}
});
function OnSuccess(response) {
var dpmale = [];
var dpfemale = [];
for (var i = 0; i < response.d.length; i++) {
var obj = response.d[i];
var datamale =
{
y: parseInt(obj.male),
label: obj.boothno,
};
var datafemale =
{
y: parseInt(obj.female),
label: obj.boothno,
};
dpmale.push(datamale);
dpfemale.push(datafemale);
}
var chart = new CanvasJS.Chart("chartContainerbar", {
animationEnabled: true,
axisX: {
interval: 1,
labelFontSize: 10,
lineThickness: 0,
},
axisY2: {
valueFormatString: "0",
lineThickness: 0,
labelFontSize: 10,
},
toolTip: {
shared: true
},
legend: {
verticalAlign: "top",
horizontalAlign: "center",
fontSize: 10,
},
data: [{
type: "stackedBar",
showInLegend: true,
name: "Male",
axisYType: "secondary",
color: "#f8d347",
dataPoints: dpmale
},
{
type: "stackedBar",
showInLegend: true,
name: "Female",
axisYType: "secondary",
color: "#6ccac9",
dataPoints: dpfemale
}
]
});
chart.render();
}
});
</script>
URL : http://canvasjs.com/

Retrieving data from ASP.net sql database into amchart

i am facing quite a problem which is to create the nice graph from http://www.amcharts.com/ but i need to retrieve data from my sql database. But i don't know how to place inside. Please guide me. Below is the way how the graph displayed, but i wanted to work with data from database. Thank you.
<script type="text/javascript">
var chartData = generateChartData();
function generateChartData() {
var chartData = [];
var firstDate = new Date(2012, 0, 1);
firstDate.setDate(firstDate.getDate() - 500);
firstDate.setHours(0, 0, 0, 0);
for (var i = 0; i < 500; i++) {
var newDate = new Date(firstDate);
newDate.setDate(newDate.getDate() + i);
var value = Math.round(Math.random() * (40 + i)) + 100 + i;
chartData.push({
date: newDate,
value: value
});
}
return chartData;
}
AmCharts.makeChart("chartdiv", {
type: "stock",
pathToImages: "../amcharts/images/",
dataSets: [{
color: "#b0de09",
fieldMappings: [{
fromField: "value",
toField: "value"
}],
dataProvider: chartData,
categoryField: "date"
}],
panels: [{
showCategoryAxis: true,
title: "Value",
eraseAll: false,
labels: [{
x: 0,
y: 100,
text: "Click on the pencil icon on top-right to start drawing",
align: "center",
size: 16
}],
stockGraphs: [{
id: "g1",
valueField: "value",
bullet: "round",
bulletColor: "#FFFFFF",
bulletBorderColor: "#00BBCC",
bulletBorderAlpha: 1,
bulletBorderThickness: 2,
bulletSize: 7,
lineThickness: 2,
lineColor: "#00BBCC",
useDataSetColors: false
}],
stockLegend: {
valueTextRegular: " ",
markerType: "none"
},
drawingIconsEnabled: true
}],
chartScrollbarSettings: {
graph: "g1"
},
chartCursorSettings: {
valueBalloonsEnabled: true
},
periodSelector: {
position: "bottom",
periods: [{
period: "DD",
count: 10,
label: "10 days"
}, {
period: "MM",
count: 1,
label: "1 month"
}, {
period: "YYYY",
count: 1,
label: "1 year"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
}]
}
});
</script>
Can you generate this script in your code behind ( using a string builder for example ) then use this
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "'" + YourStringBuild.toString() + "'", true);

How to enable working of jqgrid Filter Toolbar From Server In asp.net

Hii Guys!!!.
I developed a Jqgrid to diaplay database.Now I want to add JQgrid filter Toolbar to refine the data as per user need so i added filter toolbar.But Filter Toolbar is working with only when 'loadonce:true' means locally with first page data whereas I want it to work for whole database...from server response...
Below I am posting my code for refrence ...
$(function () {
$("#UsersGrid").jqGrid({
url: 'getGriddahico.ashx',
datatype: 'json',
height: 250,
colNames: ['UserID', 'username', 'ordinal', 'authcode', 'extension', 'trunk', 'dialnumber', 'dialdate', 'dialtime', 'duration', 'destination', 'price', 'toc'],
colModel: [
{ name: 'UserID', index: 'UserID', width: 100, sortable: true, align: 'center',hidden:true },
{ name: 'username', width: 100, sortable: true, align: 'center' },
{ name: 'ordinal', width: 100, sortable: true, align: 'center' },
{ name: 'authcode', width: 100, sortable: true },
{ name: 'extension', width: 100, sortable: true, align: 'center' },
{ name: 'trunk', width: 100, sortable: true, align: 'center' },
{ name: 'dialnumber', width: 100, sortable: true, align: 'center' },
{ name: 'dialdate', width: 100, sortable: true, align: 'center' },
{ name: 'dialtime', width: 100, sortable: true, align: 'center' },
{ name: 'duration', width: 100, sortable: true, align: 'center' },
{ name: 'destination', width: 100, sortable: true, align: 'center' },
{ name: 'price', width: 100, sortable: true, align: 'center' },
{ name: 'toc', width: 150, sortable: true, align: 'center' }
],
rowNum: 100,
rowList: [100, 200, 300],
pager: '#UsersGridPager',
sortname: 'username',
//loadonce: true,
viewrecords: true,
ignoreCase:true,
sortorder: 'asc',
autowidth: true,
toppager: true,
height: '100%'
});
$("#UsersGrid").jqGrid('navGrid', '#UsersGridPager', { edit: false, add: false, del: false, search: false });
jQuery("#UsersGrid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false });
});
My Handler(.ashx) file code:
int start=0;
int total=0;
int total_pages =0;
int intpage =Convert.ToInt32(request["page"]);
int limit=Convert.ToInt32(request["rows"]);
// int intpage = new Integer(request.getParameter("page"));
//int limit = new Integer(request.getParameter("rows"));
string sidx = request["sidx"];
string sord = request["sord"];
// String sidx = request.getParameter("sidx");
//String sord = request.getParameter("sord");
String strQuery="";
String json ="";
Boolean rc ;
MySqlDataReader rs;
//ResultSet rs = null;
if(sidx ==""){
sidx ="1";
}
/*-----------------------------------Conexión a la base de datos MySql-------------------------------------------*/
conexion conexiondb = new conexion();
conexiondb.Conectar();
/*-----------------------------------------------------------------------------------------------------------*/
total = conexiondb.countRec("price", "processeddata_table");
if( total>0 ) {
double d = Math.Ceiling( (double)(total) / (double)(limit) );
total_pages = (int)(d);
} else {
total_pages = 0;
}
if (intpage > total_pages) {
intpage=total_pages;
}
start = limit * intpage - limit;
if(start < 0 ){
start = 0;
}
//strQuery = "SELECT username,ordinal,authcode,extension,trunk,dialnumber,dialdate,dialtime,duration,destination,price,toc FROM processeddata_table ORDER BY username asc";
strQuery = "SELECT username,ordinal,authcode,extension,trunk,dialnumber,dialdate,dialtime,duration,destination,price,toc FROM processeddata_table ORDER BY " + sidx + " " + sord + " LIMIT " + start + " , " + limit;
rs = conexiondb.Consulta(strQuery);
total = conexiondb.countRec("price", "processeddata_table");
response.ContentType="text/x-json";
response.ContentType = "charset=utf-8";
//response.ContentEncoding="utf-8";
response.AddHeader("Pragma", "no-cache");
response.AddHeader("Cache-Control", "no-cache, must-revalidate");
response.AddHeader("Pragma", "no-cache");
json ="";
json = json + "{\n";
json = json + " \"page\":\""+intpage+"\",\n";
json = json + "\"total\":"+total_pages+",\n";
json = json + "\"records\":"+total+",\n";
json = json + "\"rows\": [";
rc =false;
while(rs.Read()){
if(rc){
json = json + ",";
}
json = json + "\n{";
json = json + "\"price\":\"" + Convert.ToInt32(rs["price"]) + "\",";
json = json + "\"cell\":[" + Convert.ToInt32(rs["price"]) + "";
json = json + ",\"" + Convert.ToString(rs["username"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["ordinal"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["authcode"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["extension"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["trunk"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["dialnumber"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["dialdate"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["dialtime"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["duration"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["destination"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["price"]) + "\"";
json = json + ",\"" + Convert.ToString(rs["toc"]) + "\"]";
json = json + "}";
rc=true;
}
json = json +"]\n";
json = json +"}";
HttpContext.Current.Response.Write(json);
Plz guys help me to resolve the issue..
Thanx in advance..
If you use loadonce: true option then the data will be loaded from the server at once and later searching, sorting and paging of the previously loaded data will be implemented locally by jqGrid.
If you don't want to use loadonce: true option then you have to implement the features in your server code. In the answer for example you can find an example of such implementation in the code which uses ASHX like you do.

Flot chart only displaying first series data

I'm using flot and with the JSON returned, and the initialzation provided, only the first series is visible on the chart, however, the legend displays all 3 series labels. Any Idea what I'm doing wrong?
var data = [];
function onDataReceived(seriesData) {
var options = {
series: { stack: false,
lines: { show: true, steps: false },
bars: { show: false, barWidth: 0.5, align: 'center', horizontal: true },
points: { show: true, radius: 3, symbol: 'circle' }
},
yaxis: { show: true, tickLength: 0 },
xaxis: { tickSize: [1, "month"], tickLength: 0, mode: 'time', timeformat: '%b %y' },
legend: { show: true, container: $('##(ctlId)chartLegend'), noColumns: 3 },
grid: { borderWidth: 0, hoverable: true, clickable: true }
};
var p = $.plot($('##(ctlId)'), seriesData.seriesData, options);
And My MVC Handler:
return Json(new
{
axisNames = new List<string[]>() { },
seriesData = new[]
{
new {
color = "#e17009",
label = "RN",
data = new List<string[]>() {
new string[] {DateTime.Parse("7/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "4.2"},
new string[] {DateTime.Parse("8/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "4.8"},
new string[] {DateTime.Parse("9/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.5"},
new string[] {DateTime.Parse("10/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "5.0"},
new string[] {DateTime.Parse("11/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "3.6"}
}
},
new {
color = "#ff0000",
label = "RA",
data = new List<string[]>() {
new string[] {DateTime.Parse("7/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "3.2"},
new string[] {DateTime.Parse("8/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "3.8"},
new string[] {DateTime.Parse("9/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "3.5"},
new string[] {DateTime.Parse("10/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.0"},
new string[] {DateTime.Parse("11/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.6"}
}
}
,
new {
color = "#5c9ccc",
label = "RA",
data = new List<string[]>() {
new string[] {DateTime.Parse("7/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.2"},
new string[] {DateTime.Parse("8/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.8"},
new string[] {DateTime.Parse("9/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.5"},
new string[] {DateTime.Parse("10/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "1.0"},
new string[] {DateTime.Parse("11/12/2012", System.Globalization.CultureInfo.InvariantCulture).GetJavascriptTimestamp().ToString(System.Globalization.CultureInfo.InvariantCulture), "2.4"}
}
}
}
},
JsonRequestBehavior.AllowGet);
I finally got this worked out. Flot does not seem to want to render more than one series with the use of the stack: false option when it is set to false and you are also referencing the jquery.flot.stack.js plugin. Removing the stack attribute in the code below resolved my issue. If you are not referencing the stack plugin, you can keep the stack: false attribute and it will display the additional series properly as well. Hope it helps someone.
The returned JSON was correct.
var data = [];
function onDataReceived(seriesData) {
var options = {
series: {
lines: { show: true, steps: false },
bars: { show: false, barWidth: 0.5, align: 'center', horizontal: true },
points: { show: true, radius: 3, symbol: 'circle' }
},
yaxis: { show: true, tickLength: 0 },
xaxis: { tickSize: [1, "month"], tickLength: 0, mode: 'time', timeformat: '%b %y' },
legend: { show: true, container: $('##(ctlId)chartLegend'), noColumns: 3 },
grid: { borderWidth: 0, hoverable: true, clickable: true }
};
var p = $.plot($('##(ctlId)'), seriesData.seriesData, options);

Resources