How can i populate json data into charts using ajax call? - json

I want to pass json data to jsp and populate into the charts data. How can i do this?
Previously i am setting data value by sending each value using model attribute.
In EmployeeController i have lineBarChart method like this :-
#RequestMapping("/lineBar")
public String lineBarChart(Model model)
{
List<Employee> emp = employeeMapper.getAllEmployees();
int cseCount = 0;
int ecCount = 0;
int itCount = 0;
int cseSalary = 0;
int ecSalary = 0;
int itSalary = 0;
for (int j = 0; j < emp.size(); j++)
{
if (emp.get(j).getDepartment().equalsIgnoreCase("CSE"))
{
cseSalary += emp.get(j).getSalary();
cseCount++;
}
else if (emp.get(j).getDepartment().equalsIgnoreCase("IT"))
{
itSalary += emp.get(j).getSalary();
itCount++;
}
else
{
ecSalary += emp.get(j).getSalary();
ecCount++;
}
}
Map<Integer, Integer> map = new HashMap<>();
map.put(cseCount, cseSalary);
map.put(ecCount, ecSalary);
map.put(itCount, itSalary);
GsonBuilder gsonMapBuilder = new GsonBuilder();
Gson gsonObject = gsonMapBuilder.create();
String jsonObject = gsonObject.toJson(map);
System.out.println(jsonObject);
// Previously i am doing this now i want to send json to chart
model.addAttribute("cse", cseCount);
model.addAttribute("ec", ecCount);
model.addAttribute("it", itCount);
model.addAttribute("cseSalary", cseSalary);
model.addAttribute("itSalary", itSalary);
model.addAttribute("ecSalary", ecSalary);
return "lineBarChart";
}
Here is lineBarChart.jsp :-
<script>
$(function()
{
var lineBarChart = new CanvasJS.Chart("lineBarChartContainer",
{
animationEnabled: true,
theme: "light2",
title:
{
text: "Branch wise total Employee Salary",
fontSize: 20,
fontFamily: "Trebuchet MS",
fontWeight: "bold",
margin: 10
},
axisY:
{
title: "Number of Employee",
suffix: " K"
},
data:
[{
type: "column",
dataPoints:
[
{ y: ${cse}, label: "CSE" },
{ y: ${ec}, label: "EC" },
{ y: ${it}, label: "IT" }
]
},
{
type: "line",
toolTipContent: "{label}: {y}K",
showInLegend: true,
dataPoints:
[
{ y: ${cseSalary}/10000, label: "CSE" },
{ y: ${ecSalary}/10000, label: "EC" },
{ y: ${itSalary}/10000, label: "IT" }
]
}]
});
lineBarChart.render();
});
</script>
<div class="card shadow p-3 bg-white rounded">
<div class="card-body">
<div id="lineBarChartContainer" style="height: 240px; width: 100%;"></div>
</div>
</div>
I am calling lineBarChart.jsp file from another jsp using ajax call.
Like this :-
<div class="row" >
<div class="col-md-6 p-1">
<div id="lineBarGraph"></div>
</div>
</div>
$.ajax({url: "lineBar",
async: false,
success: function(result)
{
console.log(result);
$("#lineBarGraph").html(result);
}
});

You will need to create a 2nd handler method or controller.
The existing controller will simply load the JSP so all the logic can be removed from that. The new controller method will have the logic to load and return the data requested by your Ajax call and will look like the below.
Note the #ResponseBody annotation.
Update you Ajax call to request the new path fetchChartDataor whatever you want it to be:
#RequestMapping("/fetchChartData", produces="application/json")
public #ResponseBody String getChartData()
{
List<Employee> emp = employeeMapper.getAllEmployees();
int cseCount = 0;
int ecCount = 0;
int itCount = 0;
int cseSalary = 0;
int ecSalary = 0;
int itSalary = 0;
for (int j = 0; j < emp.size(); j++)
{
if (emp.get(j).getDepartment().equalsIgnoreCase("CSE"))
{
cseSalary += emp.get(j).getSalary();
cseCount++;
}
else if (emp.get(j).getDepartment().equalsIgnoreCase("IT"))
{
itSalary += emp.get(j).getSalary();
itCount++;
}
else
{
ecSalary += emp.get(j).getSalary();
ecCount++;
}
}
Map<Integer, Integer> map = new HashMap<>();
map.put(cseCount, cseSalary);
map.put(ecCount, ecSalary);
map.put(itCount, itSalary);
//you could remove the below and return the map directly
GsonBuilder gsonMapBuilder = new GsonBuilder();
Gson gsonObject = gsonMapBuilder.create();
return gsonObject.toJson(map);
}
You could simplify further by changing the method return type to Map<Integer, Integer> and return this directly. Spring Boot will handle the serialization to Json using the configured Json library:
https://www.callicoder.com/configuring-spring-boot-to-use-gson-instead-of-jackson/

Related

How do I change an UI/Image when there's 2 gameobjects with the same name?

I'm developing an application for the hololens that generates multiple canvases with a panel with UI/Image elements. I have 1 JSON string:
{
"PC_Station":[
{
"PLC_0":{
"DB1":{
"test123":0
},
"STOP":false,
"Frap":false,
"START":false,
"Start_1":false,
"Stop_1":false,
"Led1":true,
"Led2":false,
"Led3":true,
"Counter":4002,
"Sliderval":0
}
},
{
"PLC_1":{
"DB1":{
"test123":55
},
"STOP":false,
"START":false,
"Start_1":false,
"Stop_1":false,
"Led1":true,
"Led2":false,
"Led3":true,
"Counter":4002,
"Sliderval":0
}
}
]
}
This JSON string has 2 JSON objects inside a JSON array called PLC_1 and PLC_0. PLC_1 has the same variables as PLC_0.
I've made the following function that appends the JSON and changes the color of the UI/Image objects:
IEnumerator updateTags()
{
string json = "{\"PC_Station\": [{\"PLC_1\": {\"DB1\": {\"test123\": 30}, \"STOP\": false, \"START\": true, \"Start_1\": false, \"Stop_1\": true, \"Led1\": false, \"Led2\": false, \"Led3\": false, \"Counter\": 3880, \"Sliderval\": 60}}]}";
string json1 = "{\"PC_Station\": [{\"PLC_0\": {\"DB1\": {\"test123\": 0}, \"STOP\": false,\"Frap\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}},{\"PLC_1\": {\"DB1\": {\"test123\": 55}, \"STOP\": false, \"START\": false, \"Start_1\": false, \"Stop_1\": false, \"Led1\": true, \"Led2\": false, \"Led3\": true, \"Counter\": 4002, \"Sliderval\": 0}}]}";
var data = JToken.Parse(json1);
while (true)
{
foreach (var value in data)
{
foreach(JArray arr in value)
{
for (int i = 0; i < arr.Count; i++)
{
foreach (var item in arr[i])
{
var itemproperties = item.Parent;
foreach (JToken token in itemproperties)
{
var prop = token as JProperty;
var plc = (JObject)prop.Value;
foreach (KeyValuePair<string, JToken> val in plc)
{
if(val.Value is JObject)
{
JObject nestedobj = (JObject)val.Value;
foreach (JProperty nestedvariables in nestedobj.Properties())
{
string varkey = nestedvariables.Name;
string varvalue = nestedvariables.Value.ToString();
GameObject test = GameObject.Find(varkey+"value");
test.GetComponent<Text>().text = varvalue;
}
}
else
{
for(int v = 0; v < abc.Count; v++)
{
Debug.Log(v);
foreach(KeyValuePair<string, string> variab in abc[v])
{
string varkey = val.Key;
string varvalue = val.Value.ToString();
GameObject test = GameObject.Find(varkey);
if(varvalue == "True")
{
test.GetComponent<Image>().color = Color.green;
}
if(varvalue == "False")
{
test.GetComponent<Image>().color = Color.red;
}
if(varvalue != "True" && varvalue != "False")
{
GameObject text = GameObject.Find(varkey + "value");
text.GetComponent<Text>().text = varvalue;
}
}
}
}
}
}
}
}
}
}
yield return new WaitForSeconds(0.5f);
}
}
When I run the programme, it looks like this:
As you can see, the function properly adds color to the UI/Images.
Now, for my question:
How can I make it so that the UI/Images on both canvases get filled with color despite having the same name?
There are no obvious solutions as GameObject referenes do not serialize easily, you couls reference objects by their position in the current branch of the tree (transform.GetSiblingIndex()) but that will not work if you move stuff around.
You could also just rename your objects.
Managed to fix it by using transform.find. I used it to find items in the hierarchy.
The code now functions like I want it to.
First I make a new gameobject:
public GameObject upd4;
Then I use it in my code as follows:
upd4 = transform.Find("Canvas" + i + "/Panel/" + plcvvobj.Key + "/" + plcvvobj.Key + "value").gameObject;
BTW, my hierarchy is as follows:

Transform Request to Autoquery friendly

We are working with a 3rd party grid (telerik kendo) that has paging/sorting/filtering built in. It will send the requests in a certain way when making the GET call and I'm trying to determine if there is a way to translate these requests to AutoQuery friendly requests.
Query string params
Sort Pattern:
sort[{0}][field] and sort[{0}][dir]
Filtering:
filter[filters][{0}][field]
filter[filters][{0}][operator]
filter[filters][{0}][value]
So this which is populated in the querystring:
filter[filters][0][field]
filter[filters][0][operator]
filter[filters][0][value]
would need to be translated to.
FieldName=1 // filter[filters][0][field]+filter[filters][0][operator]+filter[filters][0][value] in a nutshell (not exactly true)
Should I manipulate the querystring object in a plugin by removing the filters (or just adding the ones I need) ? Is there a better option here?
I'm not sure there is a clean way to do this on the kendo side either.
I will explain the two routes I'm going down, I hope to see a better answer.
First, I tried to modify the querystring in a request filter, but could not. I ended up having to run the autoqueries manually by getting the params and modifying them before calling AutoQuery.Execute. Something like this:
var requestparams = Request.ToAutoQueryParams();
var q = AutoQueryDb.CreateQuery(requestobject, requestparams);
AutoQueryDb.Execute(requestobject, q);
I wish there was a more global way to do this. The extension method just loops over all the querystring params and adds the ones that I need.
After doing the above work, I wasn't very happy with the result so I investigated doing it differently and ended up with the following:
Register the Kendo grid filter operations to their equivalent Service Stack auto query ones:
var aq = new AutoQueryFeature { MaxLimit = 100, EnableAutoQueryViewer=true };
aq.ImplicitConventions.Add("%neq", aq.ImplicitConventions["%NotEqualTo"]);
aq.ImplicitConventions.Add("%eq", "{Field} = {Value}");
Next, on the grid's read operation, we need to reformat the the querystring:
read: {
url: "/api/stuff?format=json&isGrid=true",
data: function (options) {
if (options.sort && options.sort.length > 0) {
options.OrderBy = (options.sort[0].dir == "desc" ? "-" : "") + options.sort[0].field;
}
if (options.filter && options.filter.filters.length > 0) {
for (var i = 0; i < options.filter.filters.length; i++) {
var f = options.filter.filters[i];
console.log(f);
options[f.field + f.operator] = f.value;
}
}
}
Now, the grid will send the operations in a Autoquery friendly manner.
I created an AutoQueryDataSource ts class that you may or may not find useful.
It's usage is along the lines of:
this.gridDataSource = AutoQueryKendoDataSource.getDefaultInstance<dtos.QueryDbSubclass, dtos.ListDefinition>('/api/autoQueryRoute', { orderByDesc: 'createdOn' });
export default class AutoQueryKendoDataSource<queryT extends dtos.QueryDb_1<T>, T> extends kendo.data.DataSource {
private constructor(options: kendo.data.DataSourceOptions = {}, public route?: string, public request?: queryT) {
super(options)
}
defer: ng.IDeferred<any>;
static exportToExcel(columns: kendo.ui.GridColumn[], dataSource: kendo.data.DataSource, filename: string) {
let rows = [{ cells: columns.map(d => { return { value: d.field }; }) }];
dataSource.fetch(function () {
var data = this.data();
for (var i = 0; i < data.length; i++) {
//push single row for every record
rows.push({
cells: _.map(columns, d => { return { value: data[i][d.field] } })
})
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: _.map(columns, d => { return { autoWidth: true } }),
// Title of the sheet
title: filename,
// Rows of the sheet
rows: rows
}
]
});
//save the file as Excel file with extension xlsx
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: filename });
})
}
static getDefaultInstance<queryT extends dtos.QueryDb_1<T>, T>(route: string, request: queryT, $q?: ng.IQService, model?: any) {
let sortInfo: {
orderBy?: string,
orderByDesc?: string,
skip?: number
} = {
};
let opts = {
transport: {
read: {
url: route,
dataType: 'json',
data: request
},
parameterMap: (data, type) => {
if (type == 'read') {
if (data.sort) {
data.sort.forEach((s: any) => {
if (s.field.indexOf('.') > -1) {
var arr = _.split(s.field, '.')
s.field = arr[arr.length - 1];
}
})
}//for autoquery to work, need only field names not entity names.
sortInfo = {
orderByDesc: _.join(_.map(_.filter(data.sort, (s: any) => s.dir == 'desc'), 'field'), ','),
orderBy: _.join(_.map(_.filter(data.sort, (s: any) => s.dir == 'asc'), 'field'), ','),
skip: 0
}
if (data.page)
sortInfo.skip = (data.page - 1) * data.pageSize,
_.extend(data, request);
//override sorting if done via grid
if (sortInfo.orderByDesc) {
(<any>data).orderByDesc = sortInfo.orderByDesc;
(<any>data).orderBy = null;
}
if (sortInfo.orderBy) {
(<any>data).orderBy = sortInfo.orderBy;
(<any>data).orderByDesc = null;
}
(<any>data).skip = sortInfo.skip;
return data;
}
return data;
},
},
requestStart: (e: kendo.data.DataSourceRequestStartEvent) => {
let ds = <AutoQueryKendoDataSource<queryT, T>>e.sender;
if ($q)
ds.defer = $q.defer();
},
requestEnd: (e: kendo.data.DataSourceRequestEndEvent) => {
new DatesToStringsService().convert(e.response);
let ds = <AutoQueryKendoDataSource<queryT, T>>e.sender;
if (ds.defer)
ds.defer.resolve();
},
schema: {
data: (response: dtos.QueryResponse<T>) => {
return response.results;
},
type: 'json',
total: 'total',
model: model
},
pageSize: request.take || 40,
page: 1,
serverPaging: true,
serverSorting: true
}
let ds = new AutoQueryKendoDataSource<queryT, T>(opts, route, request);
return ds;
}
}

JQGgrid- How to generate a pdf / excel file from the grid data

I have the following JQGrid table, which is being generated from JSON data. I want to be able to generate/export or create a pdf file based on the table data state that is view able. I am using JSON , Jqgrid and Javascript
How do I generate a pdf file from the data ?
Here My FIDDLE
JS CODE
$(document).ready(function() {
var jsonData = {
"Name": "Julie Brown",
"Account": "C0010",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "4012214.00875",
"MaxApprovedLoanAmt": "2050877.824375",
"LoanBalance": "1849000",
"AvailableCredit": "201877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "Robert L. Johnson",
"ContactPhone": "(212) 902-3614",
"RiskCategory": "Yellow",
"rows": [{
"ClientID": "C0010",
"Symbol": "WEC",
"Description": "Western Electric Co",
"ShareQuantity": "20638",
"SharePrice": "21.12",
"TotalValue": "435874.56",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "217937.28"
}, {
"ClientID": "C0010",
"Symbol": "BBB",
"Description": "Bins Breakers and Boxes",
"ShareQuantity": "9623",
"SharePrice": "74.29125",
"TotalValue": "714904.69875",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "357452.349375"
}, {
"ClientID": "C0010",
"Symbol": "GPSC",
"Description": "Great Plains Small Cap Stock",
"ShareQuantity": "49612",
"SharePrice": "14.24",
"TotalValue": "706474.88",
"LTVCategory": "Mutual Funds - Small Cap",
"LTVRatio": "40%",
"MaxLoanAmt": "282589.952"
}]
},
mmddyyyy = "";
/*********************************************************************/
$("#output").jqGrid({
url: "/echo/json/",
mtype: "POST",
datatype: "json",
postData: {
json: JSON.stringify(jsonData)
},
colModel: [
/** { name: 'ClientID', label:'ClientID',width: 80, key: true },****/
{
name: 'Symbol',
width: 65
}, {
name: 'Description',
width: 165
}, {
name: 'ShareQuantity',
align: 'right',
width: 85,
classes: "hidden-xs", labelClasses: "hidden-xs",
formatter: 'currency',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'SharePrice',
label: 'Share Price',
align: 'right',
width: 100,
classes: "hidden-xs", labelClasses: "hidden-xs",
template: "number",
formatoptions: {
prefix: " $",
decimalPlaces: 4
}
},
/*{ label: 'Value1',
name: 'Value1',
width: 80,
sorttype: 'number',
formatter: 'number',
align: 'right'
}, */
{
name: 'TotalValue',
label: 'Total Value',
width: 160,
sorttype: 'number',
align: "right",
search: false,
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}, {
name: 'LTVRatio',
label: 'LTV Ratio',
width: 70,
sorttype: 'number',
align: "right",
formatter: 'percentage',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'LTVCategory',
label: 'LTV Category',
classes: "hidden-xs", labelClasses: "hidden-xs",
width: 120,
width: 165
},
{
name: 'MaxLoanAmt',
label: 'MaxLoanAmount',
width: 165,
sorttype: 'number',
align: "right",
search: false,
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}
],
additionalProperties: ["Symbol", "Description"],
subGrid: true,
subGridRowExpanded: function (subgridDivId, rowid) {
var item = $(this).jqGrid("getLocalRow", rowid);
$("#" + $.jgrid.jqID(subgridDivId)).html("Symbol: <em>" + item.Symbol +
"</em><br/>Description: <em>" + item.Description + "</em>");
},
beforeProcessing: function (data) {
var symbolsMap = {}, symbolsValues = ":All", rows = data.rows, i, symbol;
for (i = 0; i < rows.length; i++) {
symbol = rows[i].Symbol;
if (!symbolsMap.hasOwnProperty(symbol)) {
symbolsMap[symbol] = 1;
symbolsValues += ";" + symbol + ":" + symbol;
}
}
$(this).jqGrid("setColProp", 'Symbol', {
stype: "select",
searchoptions: {
value: symbolsValues
}
}).jqGrid('destroyFilterToolbar')
.jqGrid('filterToolbar', {
stringResult: true,
searchOnEnter: false,
defaultSearch : "cn"
});
},
/*beforeProcessing: function (data) {
var item, i, n = data.length;
for (i = 0; i < n; i++) {
item = data[i];
item.Quantity = parseFloat($.trim(item.Quantity).replace(",", ""));
item.LTVRatio = parseFloat($.trim(item.LTVRatio *10000).replace(",", ""));
item.Value = parseFloat($.trim(item.Value).replace(",", ""));
item.Num1 = parseInt($.trim(item.Num1).replace(",", ""), 10);
item.Num2 = parseInt($.trim(item.Num2).replace(",", ""), 10);
}
}, */
iconSet: "fontAwesome",
loadonce: true,
rownumbers: true,
cmTemplate: {
autoResizable: true,
editable: true
},
autoResizing: {
compact: true
},
autowidth: true,
height: 'auto',
forceClientSorting: true,
sortname: "Symbol",
footerrow: true,
caption: "<b>Collateral Value</b> <span class='pull-right' style='margin-right:20px;'>Valuation as of: " + mmddyyyy + "</span>",
loadComplete: function() {
var $self = $(this),
sum = $self.jqGrid("getCol", "Price", false, "sum"),
sum1 = $self.jqGrid("getCol", "MaxLoanAmt", false, "sum");
//ltvratio = $self.jqGrid("getCol","LTVRatio:addas", "Aved Loan Amount");
$self.jqGrid("footerData", "set", {
LTVCategory: "Max Approved Loan Amount:",
Price: sum,
MaxLoanAmt: sum1
});
}
});
$("#output").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "cn"});
$(window).on("resize", function () {
var newWidth = $("#output").closest(".ui-jqgrid").parent().width();
$("#output").jqGrid("setGridWidth", newWidth, true);
}).triggerHandle("resize");
});
There is no build in method to export jqgrid data to pdf. You have to use third party tools( I personally like iTextSharp which can be downloaded from Here . You have to create action method for printing the grid data in your controller.
Here is also another one example one guy made.
Here is also another example in trirand. If you see the source code they are using iTextHsarp.
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JQGridMVCExamples.Models;
using Trirand.Web.Mvc;
using System.IO;
//
// For PDF export we are using the free open-source iTextSharp library.
//
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;
namespace JQGridMVCExamples.Controllers.Grid
{
public partial class GridController : Controller
{
// This is the default action for the View. Use it to setup your grid Model.
public ActionResult ExportPDF()
{
// Get the model (setup) of the grid defined in the /Models folder.
var gridModel = new OrdersJqGridModel();
var ordersGrid = gridModel.OrdersGrid;
// Setting the DataUrl to an action (method) in the controller is required.
// This action will return the data needed by the grid
ordersGrid.DataUrl = Url.Action("PDFGrid_DataRequested");
// customize the default Orders grid model with custom settings
// NOTE: you need to call this method in the action that fetches the data as well,
// so that the models match
SetPDFExportGrid(ordersGrid);
// Pass the custmomized grid model to the View
return View(gridModel);
}
// This method is called when the grid requests data
public JsonResult PDFGrid_DataRequested()
{
// Get both the grid Model and the data Model
// The data model in our case is an autogenerated linq2sql database based on Northwind.
var gridModel = new OrdersJqGridModel();
var northWindModel = new NorthwindDataContext();
// customize the default Orders grid model with our custom settings
SetPDFExportGrid(gridModel.OrdersGrid);
// Save the current grid state in Session
// We will later need it for PDF Export
JQGridState gridState = gridModel.OrdersGrid.GetState();
Session["gridState"] = gridState;
// return the result of the DataBind method, passing the datasource as a parameter
// jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
return gridModel.OrdersGrid.DataBind(northWindModel.Orders);
}
public JsonResult PDFExport_AutoCompleteShipName(string term)
{
var northWindModel = new NorthwindDataContext();
JQAutoComplete autoComplete = new JQAutoComplete();
autoComplete.DataField = "ShipName";
autoComplete.AutoCompleteMode = AutoCompleteMode.BeginsWith;
autoComplete.DataSource = from o in northWindModel.Orders
select o;
return autoComplete.DataBind();
}
private void SetPDFExportGrid(JQGrid ordersGrid)
{
// show the search toolbar
ordersGrid.ToolBarSettings.ShowSearchToolBar = true;
ordersGrid.ToolBarSettings.ShowSearchButton = true;
var orderDateColumn = ordersGrid.Columns.Find(c => c.DataField == "OrderDate");
orderDateColumn.DataFormatString = "{0:yyyy/MM/dd}";
orderDateColumn.SearchType = SearchType.DatePicker;
orderDateColumn.DataType = typeof(DateTime);
orderDateColumn.SearchControlID = "DatePicker";
orderDateColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;
var shipNameColumn = ordersGrid.Columns.Find(c => c.DataField == "ShipName");
shipNameColumn.SearchType = SearchType.AutoComplete;
shipNameColumn.DataType = typeof(string);
shipNameColumn.SearchControlID = "AutoComplete";
shipNameColumn.SearchToolBarOperation = SearchOperation.Contains;
var orderIDColumns = ordersGrid.Columns.Find(c => c.DataField == "OrderID");
orderIDColumns.Searchable = true;
orderIDColumns.DataType = typeof(int);
orderIDColumns.SearchToolBarOperation = SearchOperation.IsEqualTo;
SetPDFCustomerIDSearchDropDown(ordersGrid);
SetPDFFreightSearchDropDown(ordersGrid);
}
private void SetPDFCustomerIDSearchDropDown(JQGrid ordersGrid)
{
// setup the grid search criteria for the columns
JQGridColumn customersColumn = ordersGrid.Columns.Find(c => c.DataField == "CustomerID");
customersColumn.Searchable = true;
// DataType must be set in order to use searching
customersColumn.DataType = typeof(string);
customersColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;
customersColumn.SearchType = SearchType.DropDown;
// Populate the search dropdown only on initial request, in order to optimize performance
if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
{
var northWindModel = new NorthwindDataContext();
var searchList = from customers in northWindModel.Customers
select new SelectListItem
{
Text = customers.CustomerID,
Value = customers.CustomerID
};
customersColumn.SearchList = searchList.ToList<SelectListItem>();
customersColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
}
}
private void SetPDFFreightSearchDropDown(JQGrid ordersGrid)
{
// setup the grid search criteria for the columns
JQGridColumn freightColumn = ordersGrid.Columns.Find(c => c.DataField == "Freight");
freightColumn.Searchable = true;
// DataType must be set in order to use searching
freightColumn.DataType = typeof(decimal);
freightColumn.SearchToolBarOperation = SearchOperation.IsGreaterOrEqualTo;
freightColumn.SearchType = SearchType.DropDown;
// Populate the search dropdown only on initial request, in order to optimize performance
if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
{
List<SelectListItem> searchList = new List<SelectListItem>();
searchList.Add(new SelectListItem { Text = "> 10", Value = "10" });
searchList.Add(new SelectListItem { Text = "> 30", Value = "30" });
searchList.Add(new SelectListItem { Text = "> 50", Value = "50" });
searchList.Add(new SelectListItem { Text = "> 100", Value = "100" });
freightColumn.SearchList = searchList.ToList<SelectListItem>();
freightColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
}
}
public ActionResult ExportToPDF(string exportType)
{
var gridModel = new OrdersJqGridModel();
var northWindModel = new NorthwindDataContext();
var grid = gridModel.OrdersGrid;
// Get the last grid state the we saved before in Session in the DataRequested action
JQGridState gridState = Session["GridState"] as JQGridState;
// Need to set grid options again
SetExportGrid(grid);
if (String.IsNullOrEmpty(exportType))
exportType = "1";
DataTable exportData;
switch (exportType)
{
case "1":
grid.ExportSettings.ExportDataRange = ExportDataRange.All;
exportData = grid.GetExportData(northWindModel.Orders);
ExportToPDF(exportData);
break;
case "2":
grid.ExportSettings.ExportDataRange = ExportDataRange.Filtered;
exportData = grid.GetExportData(northWindModel.Orders, gridState);
ExportToPDF(exportData);
break;
case "3":
grid.ExportSettings.ExportDataRange = ExportDataRange.FilteredAndPaged;
exportData = grid.GetExportData(northWindModel.Orders, gridState);
ExportToPDF(exportData);
break;
}
return View();
}
private void ExportToPDF(DataTable dt)
{
//
// For PDF export we are using the free open-source iTextSharp library.
//
Document pdfDoc = new Document();
MemoryStream pdfStream = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);
pdfDoc.Open();//Open Document to write
pdfDoc.NewPage();
Font font8 = FontFactory.GetFont("ARIAL", 7);
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
//Add Header of the pdf table
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].Caption, font8)));
PdfTable.AddCell(PdfPCell);
}
//How add the data from datatable to pdf table
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
pdfDoc.Add(PdfTable); // add pdf table to the document
pdfDoc.Close();
pdfWriter.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=gridexport.pdf");
Response.BinaryWrite(pdfStream.ToArray());
Response.End();
}
}
}

Jqgrid not binding after returning json text

Unable to bind my JQgrid, below is my code:
Trying to bind some data to jqgrid through controller using Json but not able to bind the grid. attached my code below.
Controller Class:
public class TransactionTypeController : Controller
{
//
// GET: /TransactionType/
public ActionResult Index(EMM_New.Models.TransactionTypeModal TransactionType)
{
List<EMM_New.Models.TransactionTypeEntity> lst = TransactionType.GetTransactionType();
ViewBag.TransactionTypeData = lst;
return View();
}
public ActionResult GetGridData(string sidx, string sord, int page, int rows)
{
return Content(JsonHelper.JsonForJqgrid(GetDataTable(sidx, sord, page, rows), rows, GetTotalCount(), page), "application/json");
}
public DataTable GetDataTable(string sidx, string sord, int page, int pageSize)
{
int startIndex = (page - 1) * pageSize;
int endIndex = page * pageSize;
DataTable table = new DataTable();
table.Columns.Add("CustomerID", typeof(int));
table.Columns.Add("ContactName", typeof(string));
table.Columns.Add("Address", typeof(string));
table.Columns.Add("City", typeof(string));
table.Columns.Add("PostalCode", typeof(string));
//
// Here we add five DataRows.
//
table.Rows.Add(25, "Ramesh", "Combivent", "Bangalore", "463456");
table.Rows.Add(50, "Sam", "Enebrel", "Hosur", "463456");
table.Rows.Add(10, "Christoff", "Hydralazine", "Bangalore", "463456");
table.Rows.Add(21, "Janet", "Combivent", "Hosur", "463456");
table.Rows.Add(100, "Melanie", "Dilantin", "Bangalore", "463456");
return table;
}
public int GetTotalCount() {
return 10;
}
}
JsonHelper Class:
public class JsonHelper
{
public static string JsonForJqgrid(DataTable dt, int pageSize, int totalRecords, int page)
{
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{");
jsonBuilder.Append("\"total\":" + totalPages + ",\"page\":" + page + ",\"records\":" + (totalRecords) + ",\"rows\"");
jsonBuilder.Append(":[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{\"i\":" + (i) + ",\"cell\":[");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
}
View:
<table id="list" class="scroll" >
</table>
<div id="pager" class="scroll" style="text-align: center;">
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#list").jqGrid({
url: '/TransactionType/GetGridData/',
datatHomeype: 'json',
mtype: 'GET',
colNames: ['Customer ID', 'Contact Name', 'Address', 'City', 'Postal Code'],
colModel: [
{ name: 'CustomerID', index: 'CustomerID', width: 100, align: 'left' },
{ name: 'ContactName', index: 'ContactName', width: 150, align: 'left' },
{ name: 'Address', index: 'Address', width: 300, align: 'left' },
{ name: 'City', index: 'City', width: 150, align: 'left' },
{ name: 'PostalCode', index: 'PostalCode', width: 100, align: 'left' }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'CustomerID',
sortorder: "asc",
viewrecords: true,
caption: 'JqGrid from class Binding'
}).navGrid(pager, { edit: false, add: false, del: false, refresh: true, search: true });
});
</script>
Able to see the Jqgrid, but data is not populating....What i'm doing worng.Please some help me in sorting this out..
datatHomeype: 'json'?
Should be datatype: 'json'
Try to change your json like this:
{"total":1,"page":"1","records":10,"rows":[{"cell":["25","Ram","Combivent","Bangalore","463456"]}]}

ExtJs Tree Panel not loaded from .NET webservice JSON response

I am making a ExtJS tree panel to load it from JSON response from .NET web service.
it seems I got the correct json response, as when I directly apply the response to store it shows the tree, can any one help me where I am doing wrong.
following is my code:
Ext.onReady(function () {
var mystore = Ext.create('Ext.data.TreeStore',
{
autoLoad: true,
root: {
text: 'Root',
expanded: true//,
//id: 'ID'
},
proxy: {
type: 'ajax',
url: 'FirstService.asmx/GetTreeNodes',
reader:
{
type: 'json'
}
}
});
Ext.create('Ext.tree.Panel', {
title: 'Simple Tree',
width: 200,
height: 300,
useArrows: true,
rootVisible: false,
store: mystore,
renderTo: 'mydiv'
});
});
My websrevice code is like:
public class TreeNode
{
public int ID { get; set; }
public string text { get; set; }
public bool leaf { get; set; }
public List<TreeNode> children { get; set; }
}
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false, XmlSerializeString = false)]
public void GetTreeNodes()
{
List<TreeNode> list = new List<TreeNode>();
for (int i = 1; i <= 4; i++)
{
TreeNode parent = new TreeNode();
parent.ID = i;
parent.text = "Nodes." + i;
parent.leaf = false;
parent.children = new List<TreeNode>();
for (int j = 1; j <= 2; j++)
{
TreeNode child = new TreeNode();
child.ID = i * 10 + j;
child.text = "Nodes." + child.ID;
child.leaf = true;
parent.children.Add(child);
}
list.Add(parent);
}
string jsonResult = new JavaScriptSerializer().Serialize(list.ToList());
//{"success": true,"root":[{"ID":1,"text":"Nodes.1","leaf":false,"children":[{"ID":11,"text":"Nodes.11","leaf":true,"children":null},{"ID":12,"text":"Nodes.12","leaf":true,"children":null}]},{"ID":2,"text":"Nodes.2","leaf":false,"children":[{"ID":21,"text":"Nodes.21","leaf":true,"children":null},{"ID":22,"text":"Nodes.22","leaf":true,"children":null}]},{"ID":3,"text":"Nodes.3","leaf":false,"children":[{"ID":31,"text":"Nodes.31","leaf":true,"children":null},{"ID":32,"text":"Nodes.32","leaf":true,"children":null}]},{"ID":4,"text":"Nodes.4","leaf":false,"children":[{"ID":41,"text":"Nodes.41","leaf":true,"children":null},{"ID":42,"text":"Nodes.42","leaf":true,"children":null}]}]}
//{ root: { expanded: true, children:
jsonResult = "{ root: { expanded: true, children: " + jsonResult + "}}";
System.Web.HttpContext.Current.Response.ContentType = "application/json";
System.Web.HttpContext.Current.Response.Write(jsonResult);
}
Myjson response is like, what i see in FF consol window
{ root: { expanded: true, children: [{"ID":1,"text":"Nodes.1","leaf":false,"children":[{"ID":11,"text":"Nodes.11","leaf":true,"children":null},{"ID":12,"text":"Nodes.12","leaf":true,"children":null}]},{"ID":2,"text":"Nodes.2","leaf":false,"children":[{"ID":21,"text":"Nodes.21","leaf":true,"children":null},{"ID":22,"text":"Nodes.22","leaf":true,"children":null}]},{"ID":3,"text":"Nodes.3","leaf":false,"children":[{"ID":31,"text":"Nodes.31","leaf":true,"children":null},{"ID":32,"text":"Nodes.32","leaf":true,"children":null}]},{"ID":4,"text":"Nodes.4","leaf":false,"children":[{"ID":41,"text":"Nodes.41","leaf":true,"children":null},{"ID":42,"text":"Nodes.42","leaf":true,"children":null}]}]}}
if I directly use this response in Store it loads the tree, please kindly help me here. thanks