If any possibility connects database in amcharts (pie Chart) in asp.net? - c#

<---- This below code used for PieChart.aspx.cs ---->
protected void Page_Load(object sender, EventArgs e)
{
}
public chart ChartUser(string UserId)
{
chart c = new chart();
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=emp;Integrated Security=True");
// SqlDataAdapter da = new SqlDataAdapter("select * from ChartPie where id= UserId + "'", con);
con.Open();
SqlCommand cmd = new SqlCommand("select * from ChartPie where id='" + UserId + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
c.UserId = dr["UserId"].ToString();
c.Language = dr["Language"].ToString();
c.percentage = dr["percentage"].ToString();
}
return c;
}
public class chart
{
public string UserId { get; set; }
public string Language { get; set; }
public string percentage { get; set; }
}
}
<---- give below code used for script file ----->
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"theme": "none",
"legend": {
"markerType": "circle",
"position": "right",
"marginRight": 80,
"autoMargins": false
},
"dataProvider": [{
"Language": "Tamil",
"percentage": 50
}, {
"Language": "English",
"percentage": 40
}, {
"Language": "Hindi",
"percentage": 30
}],
"valueField": "percentage",
"titleField": "Language",
colorField: "color",
"balloonText": "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>",
"exportConfig": {
"menuTop": "0px",
"menuItems": [{
"icon": '/lib/3/images/export.png',
"format": 'png'
}]
}
});
Kindly tell me how can I get value from database?

Modify the script like this. Send the Ajax request to the asp.net page and assign the result to the AmChars dataprovider.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PieChart.aspx/ChartUser",
data: "{UserId : '123'}",
dataType: "json",
success: function (data) {
AmCharts.makeChart("chartdiv", {
"type": "pie",
"theme": "none",
"legend": {
"markerType": "circle",
"position": "right",
"marginRight": 80,
"autoMargins": false
},
"dataProvider": [data.chart],
"valueField": "percentage",
"titleField": "Language",
colorField: "color",
"balloonText": "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>",
"exportConfig": {
"menuTop": "0px",
"menuItems": [{
"icon": '/lib/3/images/export.png',
"format": 'png'
}]
}
});
},
error: function (result) {
alert("Error");
}
});
});
</script>

Reverting data from database using Amchats and Asp.net.
Here in this Example i am using Line chatsIt worked for me
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
<script src="JSfiles/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var chartDataResults = new Array();
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'sampleLine.aspx/GetDataonload',
data: {},
success:
function (response) {
drawVisualization(response.d);
}
});
function drawVisualization(dataValues) {
for (var i = 0; i < dataValues.length; i++) {
var dataitem = dataValues[i];
var date = dataitem.date;
var cpa = dataitem.cpacount;
//alert(cpa);
var cpi = dataitem.cpicount;
var cpm = dataitem.cpmcount;
chartDataResults.push({
date: date,
cpacount: cpa,
cpicount: cpi,
cpmcount: cpm
});
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"marginRight": 30,
"legend": {
"equalWidths": false,
"periodValueText": "total: [[value.sum]]",
"position": "top",
"valueAlign": "left",
"valueWidth": 100
},
"dataProvider":chartDataResults,
//"dataProvider": [{
// "year": 1994,
// "cars": 1587,
// "motorcycles": 650,
// "bicycles": 121
//}],
"valueAxes": [{
"stackType": "regular",
"gridAlpha": 0.07,
"position": "left",
"title": "Traffic incidents"
}],
"graphs": [{
"balloonText": "<img src='images/icons-02.jpg' style='vertical-align:bottom; margin-right: 10px; width:28px; height:21px;'><span style='font-size:14px; color:#000000;'><b>[[value]]</b></span>",
"fillAlphas": 0.6,
"hidden": true,
"lineAlpha": 0.4,
"title": "CPA Count",
"valueField": "cpacount"
}, {
"balloonText": "<img src='images/icons-03.jpg' style='vertical-align:bottom; margin-right: 10px; width:28px; height:21px;'><span style='font-size:14px; color:#000000;'><b>[[value]]</b></span>",
"fillAlphas": 0.6,
"lineAlpha": 0.4,
"title": "CPI Count",
"valueField": "cpicount"
}, {
"balloonText": "<img src='images/icons-04.jpg' style='vertical-align:bottom; margin-right: 10px; width:28px; height:21px;'><span style='font-size:14px; color:#000000;'><b>[[value]]</b></span>",
"fillAlphas": 0.6,
"lineAlpha": 0.4,
"title": "CPM Count",
"valueField": "cpmcount"
}],
"plotAreaBorderAlpha": 0,
"marginTop": 10,
"marginLeft": 0,
"marginBottom": 0,
"chartScrollbar": {},
"chartCursor": {
"cursorAlpha": 0
},
"categoryField": "date",
"categoryAxis": {
"startOnAxis": true,
"axisColor": "#DADADA",
"gridAlpha": 0.07,
"title": "Year",
"guides": [{
category: "2001",
toCategory: "2016",
lineColor: "#CC0000",
lineAlpha: 1,
fillAlpha: 0.2,
fillColor: "#CC0000",
dashLength: 2,
inside: true,
labelRotation: 90,
label: "Increased Count"
}, {
category: "2016",
lineColor: "#CC0000",
lineAlpha: 1,
dashLength: 2,
inside: true,
labelRotation: 90,
label: "Count"
}]
},
"export": {
"enabled": true
}
});
}
}
});
</script>
C# code:
[WebMethod]
public static List<ChartDetails> GetDataonload()
{
string Constring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
using (SqlConnection con = new SqlConnection(Constring))
{
List<ChartDetails> dataList = new List<ChartDetails>();
SqlCommand cmd = new SqlCommand("Usp_TotalcountCPA_new_usingfunction", con);
cmd.CommandTimeout = 50;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#iAdvertiserid", "1000120");
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
foreach (DataRow dtrow in dt.Rows)
{
ChartDetails details = new ChartDetails();
string date = dtrow[4].ToString();
details.date = date.Substring(3, 7);
details.cpacount = dtrow[7].ToString();
details.cpicount = dtrow[10].ToString();
details.cpmcount = dtrow[14].ToString();
details.cvpcount = dtrow[16].ToString();
dataList.Add(details);
}
return dataList;
}
}
public class ChartDetails
{
public string date { get; set; }
public string cpacount { get; set; }
public string cpicount { get; set; }
public string cpmcount { get; set; }
public string cvpcount { get; set; }
// public string CountryCode { get; set; }
}

Retrieving data from database using pi charts in Amcharts
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/pie.js"></script>
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
<script src="JSfiles/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var chartDataResults = new Array();
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'pichartssimple.aspx/GetDataonload',
data: {},
success: function (response) {
drawchart(response.d); // calling method
},
error: function () {
alert("Error:Something went wrong.Contact the Adminstrator");
alert(response);
}
});
function drawchart(dataValues) {
for (var i = 0; i < dataValues.length; i++) {
// data.addRow([dataValues[i].Accounts, dataValues[i].Accountvalues]);
var dataitem = dataValues[i];
var Account = dataitem.Accounts;
var Accountvalues = dataitem.Accountvalues;
// alert(Accountvalues);
chartDataResults.push({
Account: Account,
Accountvalues: Accountvalues
});
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"theme": "light",
"dataProvider": chartDataResults,
"valueField": "Accountvalues",
"titleField": "Account",
"balloon": {
"fixedPosition": true
},
"export": {
"enabled": true
}
});
}
// Instantiate and draw our chart, passing in some option
}
});
</script>
C#code
[WebMethod(EnableSession = true)]
public static List<Chatdata> GetDataonload()
{
List<Chatdata> dataList = new List<Chatdata>();
using (SqlConnection con = new SqlConnection("Data Source=203.115.195.52;Initial Catalog=mcom_ad_engine;Persist Security Info=True;User ID=appl;Password=mcom007;"))
{
//string StartDate = DateTime.Now.AddDays(-180).ToString("yyyy-MM-dd");
string StartDate = DateTime.Now.AddDays(-60).ToString("yyyy-MM-dd");
string EndDate = DateTime.Now.ToString("yyyy-MM-dd");
SqlCommand cmd = new SqlCommand("Sp_Advertiser_Monthly_payout_pichat", con);
cmd.CommandTimeout = 50;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#iAdvertiser", "1000120");
cmd.Parameters.AddWithValue("#istartdate", StartDate);
cmd.Parameters.AddWithValue("#ienddate", EndDate);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
foreach (DataRow dtrow in dt.Rows)
{
if (dtrow[0].ToString() != "Spent")
{
Chatdata details = new Chatdata();
details.Accounts = dtrow[0].ToString();
// details.spent = Convert.ToInt64(dtrow[2].ToString());
if (dtrow[1].ToString().StartsWith("-"))
{
string bal = dtrow[1].ToString();
bal = bal.Substring(1, bal.Length - 1);
details.Accountvalues = Convert.ToInt64(bal);
}
else
{
details.Accountvalues = Convert.ToInt64(dtrow[1].ToString());
}
dataList.Add(details);
}
}
return dataList;
}
}
public class Chatdata
{
public string Accounts { get; set; }
public Int64 Accountvalues { get; set; }
}

Related

Invalid data table format: column #1 must be of type 'date,number,datetime

i am workning with google charts and i'am try to do timeline chart but i have this error(Invalid data table format: column #1 must be of type 'date,number,datetime) where i retrieve the data from my web service my data like(Name,StartDate,EndDate)
google.charts.load('current', { 'packages': ['timeline'] });
google.charts.setOnLoadCallback(draw_Charts);
function draw_Charts() {
var options = {
backgroundColor: 'transparent',
width: '100%',
height: 400,
title: '',
titleTextStyle: {
fontSize: 20,
},
legend: { position: 'left', textStyle: { fontSize: '40%' } },
colors: ['#4285F4', '#007E33', '#ffbb33']
};
$.ajax({
type: "POST",
url: "Project_Data.asmx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.Timeline($("#timeline")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.status + " - " + r.statusText);
},
error: function (r) {
alert(r.status + " - " + r.statusText);
}
});
}
this my methode from my web service to retrieve data it's working fine and when calling this method get data like this example "Nam1","2020-09-01","2020-09-30"
public List<object[]> GetChartData()
{
string query = #"My query";
List<object[]> chartData = new List<object[]>();
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
var date = DateTime.Parse(sdr[3].ToString()).ToString("yyyy-MM-dd"); ;
var date2 = DateTime.Parse(sdr[4].ToString()).ToString("yyyy-MM-dd");
chartData.Add(new object[]
{
sdr[0],date,date2
});
}
sdr.Close();
}
con.Close();
return chartData;
}
}
}
please someone have any idea ?
the error occurs because the date values are coming across as strings in the JSON.
"2020-09-01"
need to convert to actual date objects, before building the google data table.
new Date("2020-09-01");
you can use the following to convert the values for each row, replace...
var data = google.visualization.arrayToDataTable(r.d);
with...
var data = google.visualization.arrayToDataTable(r.d.map(function (row, rowIndex) {
if (rowIndex === 0) {
// column headings
return row;
} else {
// column values
return row.map(function (col, colIndex) {
if (colIndex === 0) {
// name column
return col;
} else {
// date column
return new Date(col);
}
});
}
}));
see following working example...
google.charts.load('current', {
packages: ['timeline']
}).then(function () {
var options = {
backgroundColor: 'transparent',
width: '100%',
height: 400,
title: '',
titleTextStyle: {
fontSize: 20,
},
legend: { position: 'left', textStyle: { fontSize: '40%' } },
colors: ['#4285F4', '#007E33', '#ffbb33']
};
var r = {};
r.d = [
["name","start","end"],
["Nam1","2020-09-01","2020-09-30"],
["Nam2","2020-09-14","2020-09-30"]
];
var data = google.visualization.arrayToDataTable(r.d.map(function (row, rowIndex) {
if (rowIndex === 0) {
// column headings
return row;
} else {
// column values
return row.map(function (col, colIndex) {
if (colIndex === 0) {
// name column
return col;
} else {
// date column
return new Date(col);
}
});
}
}));
var chart = new google.visualization.Timeline($("#timeline")[0]);
chart.draw(data, options);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline"></div>

Display SQL Data using Ajax & jQuery from SQL using C# WebMethod in Chart.Js

I'm looking to display two columns; Description and ApplicantSourceCount in a Chart.js Bar Chart using C# Webmethod and the below jQuery/Ajax code.
I can't seem to pull the data into the chart to display, I keep getting and error stating that Uncaught ReferenceError: Description is not defined Is anyone able to assist in how it should be structured?
I've checked multiple different source but can't get anything to work.
SQL Data Example:
Description | ApplicantSourceCount
Reed | 48
Indeed | 38
TotalJobs | 43
jQuery/Ajax Code;
jQuery(document).ready(function () {
console.log( "ready!" );
jQuery.ajax({
type: "POST",
url: "ReportingDashboard.aspx/GetApplicantSourceData",
data: '{aData:' + Description + ApplicationSourceCount + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall_
});
function OnSuccess(reponse) {
var aData = response.d;
var aLabels = aData[0];
var datasetAppSource1 = aData[1];
var datasetAppSource2 = aData[2];
var data = {
labels: aLabels,
datasets: [{
label: "Description",
data: datasetAppSource1,
borderColor: "rgba(0, 123, 255, 0.9)",
borderWidth: "0",
backgroundColor: "rgba(0, 123, 255, 0.5)"
},
{
label: "ApplicantSourceCount",
data: datasetAppSource2,
borderColor: "rgba(0, 123, 255, 0.9)",
borderWidth: "0",
backgroundColor: "rgba(0, 123, 255, 0.5)"
}]
};
//bar chart
var ctx = document.getElementById("barChart");
ctx.height = 200;
var barChart = new Chart(ctx).Line(date, {
bezierCurve: false
});
}
function OnErrorCall_(repo) {
alert("Error Loading Data");
}
});
C# Web Method
[WebMethod]
public List<ApplicantSourceData> GetApplicantSourceData(List<string> aData)
{
//SqlDataReader reader;
List<ApplicantSourceData> GetApplicantSourceData = new List<ApplicantSourceData>();
string connectionString = ConfigurationManager.ConnectionStrings["ATL2"].ConnectionString;
string commandTextApplicantsByMonthCount = Properties.Queries.commandTextApplicantsByMonthCount;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(commandTextApplicantsByMonthCount))
{
command.CommandText = commandTextApplicantsByMonthCount;
command.CommandType = CommandType.Text;
command.Connection = con;
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
int counter = 0;
while (reader.Read())
{
ApplicantSourceData tsData = new ApplicantSourceData();
tsData.Description = reader["Description"].ToString();
tsData.ApplicantSource = reader["ApplicantSourceCount"].ToString();
GetApplicantSourceData.Add(tsData);
counter++;
}
}
}
return GetApplicantSourceData;
}
}

Return Dynamic Array From Controller Asp.Net MVC

I can generate a Pie Chart Just like the picture by using the code below
<script>
var pieChartData = [
{ label: "Data 1", data: 16, color: "#62cb31", },
{ label: "Data 2", data: 6, color: "#A4E585", },
{ label: "Data 3", data: 22, color: "#368410", },
{ label: "Data 4", data: 32, color: "#8DE563", }
];
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
</script>
Now what I want to do is to generate the var data = [] dynamically from Controller. How to do this? Also the data is from the Database.
By Combining Pranav Patel and Ghanshyam Singh answers
I was able able to reach the desired output
Model
public class GenderPieChart_Model
{
public string GenderDesc { get; set; }
public int GenderID { get; set; }
}
Controller
public JsonResult Gender()
{
Dashboard_Layer data = new Dashboard_Layer();
var lst = data.Gender();
return Json(lst, JsonRequestBehavior.AllowGet);
}
Business Layer
public IEnumerable<GenderPieChart_Model> Gender()
{
List<GenderPieChart_Model> data = new List<GenderPieChart_Model>();
using (SqlConnection con = new SqlConnection(Connection.MyConn()))
{
SqlCommand com = new SqlCommand("dbo.sp_Project_DashBoard 4", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
GenderPieChart_Model value = new GenderPieChart_Model();
value.GenderDesc = Convert.ToString(reader.GetValue(0));
value.GenderID = Convert.ToInt32(reader.GetValue(1));
data.Add(value);
}
}
return data;
}
View
<div class="flot-chart-content" id="_ByGender" style="height: 150px"></div>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "#Url.Action("Gender", "Dashboard")",
content: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = data;
var pieChartData = [];
$.each(data, function (i,v) {
pieChartData.push({ label: v.GenderDesc, data: v.GenderID, color: "#62cb31", });
})
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByGender"), pieChartData, pieChartOptions);
}
})
});
</script>
you can call when your controller on ready event and after getting data (returned Json from your controller) can process further. You can try like below
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "<YOUR URL>",
data: "<YOUR PARAMETER IF NEEDED>",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){ //data is your json returned from controller
var myData = JSON.parse(data);
//create your 'pieChartData' from object 'myData'
//pieChartData =
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
}
});
});
</script>
Its simple just return Json from your controller:
first create a model class for the properties
public class Chart
{
public string label{get;set;}
public string data{get;set;}
public string color{get;set;}
}
MVC action method:-
public JsonResult Chart()
{
List<Chart> chartList=new List();
// Code to fetch Data in List chartList
return Json(chartList,JsonRequestBehaviour.AllowGet);
}
Ajax Call:-
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "/Controller/Chart",
data: "<YOUR PARAMETER IF NEEDED>",
dataType: "json",
success: function(data){
$.each(data,function(i,index){
// Code to plot Chart here
});
}
});
});
</script>

Connecting JQGRID with MYSQL & ASP.NET

Im Currently Stack on how to display all the data of my database im new in using JQGRID and i dont know why is my data dont display when i deployed it on web using localhost
getdata.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Services;
using System.Web.Script.Services;
using MySql.Data.MySqlClient;
public partial class getdata : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public struct s_GridResult
{
public int page;
public int total;
public int record;
public s_RowData[] rows;
}
public struct s_RowData
{
public int id;
public string[] cell;
}
[WebMethod]
public static s_GridResult GetDataTable(string _search, string nd, int rows, int page,
string sidx, string sord)
{
int startindex = (page - 1);
int endindex = page;
string sql = "SELECT ItemCode,PartNumber FROM tblitemcodefromqne";
DataTable dt = new DataTable();
MySqlConnection conn = new
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString);
MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn);
adapter.Fill(dt);
s_GridResult result = new s_GridResult();
List<s_RowData> rowsadded = new List<s_RowData>();
int idx = 1;
foreach (DataRow row in dt.Rows)
{
s_RowData newrow = new s_RowData();
newrow.id = idx++;
newrow.cell = new string[2]; //total number of columns
newrow.cell[0] = row[0].ToString();
newrow.cell[1] = row[1].ToString();
rowsadded.Add(newrow);
}
result.rows = rowsadded.ToArray();
result.page = page;
result.total = dt.Rows.Count;
result.record = rowsadded.Count;
return result;
}
}
getdata.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1
/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link rel="Stylesheet" type="text/css" media="screen" href="JQGridReq/jquery-
ui-1.9.2.custom.css" />
<link rel="Stylesheet" type="text/css" media="screen" href="JQGridReq/ui.jqgrid.css" />
<link rel="Stylesheet" type="text/css" media="screen" href="Themes/style.css" />
<script type="text/javascript" src="JQGridReq/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="JQGridReq/jquery.json-2.2.min.js"></script>
<script type="text/javascript" src="JQGridReq/jquery-ui-1.9.4.custom.min.js"></script>
<script type="text/javascript" src="JQGridReq/grid.locale-en.js"></script>
<script type="text/javascript" src="JQGridReq/jquery.jqGrid.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$.extend($.jgrid.defaults,
{ datatype: 'json' },
{ ajaxGridOptions: { contentType: "application/json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#Grid1")[0];
thegrid.addJSONData(data.d);
thegrid.grid.hDiv.loading = false;
switch (thegrid.p.loadui) {
case "disable":
break;
case "enable":
$("#load_" + thegrid.p.id).hide();
break;
case "block":
$("#lui_" + thegrid.p.id).hide();
$("#load_" + thegrid.p.id).hide();
break;
}
}
}
}
});
jQuery("#Grid1").jqGrid({
url: 'getdata.aspx/GetDataTable',
datatype: 'json',
mtype: 'POST',
colNames: ['Item Code', 'Part Number'],
colModel: [{ name: 'ItemCode', index: 'ItemCode', width: 200 },
{ name: 'PartNumber', index: 'PartNumber', width: 300}],
pager: '#pager', sortname: 'ItemCode',
viewrecoreds: true,
imgpath: 'JQGridReq/images',
serializeGridData: function (data) {
return $.toJSON(data);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="Grid1" class="scroll" align="center" width="100%"></table>
<div id="pager" class="scroll" style="text-align:center;">
</div>
</form>
</body>
</html>
The field names of the database table should match with the name in the colmodel which is in the javascript.
The java script
<script language="javascript" type="text/javascript">
$(function() {
var grid = jQuery("#myGrid");
grid.jqGrid({
url: "http://localhost:50530/jqGridHandler.ashx",
mtype:'GET',
datatype: "json",
height: 200,
hidegrid: false,//hides the arrow button at the top right corner for collapsing the jqGrid
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
caption: "Employees",
pager: "#pager",
colNames: ['FirstName', 'SecondName', 'DOB', 'EmailID','UserName'],
colModel: [
{ name: 'FirstName', index: 'FirstName', width: 100, align: "center" },
{ name: 'LastName', index: 'LastName', width: 100, align: "left" },
{ name: 'DOB', index: 'DOB', width: 100, align: "center", formatter: 'date', formatoptions: { newformat: 'm-d-Y' }, datefmt: 'm-d-Y' },
{ name: 'Email', index: 'EmailID', width: 120, align: "right"},
{ name: 'Username', index: 'Username', width: 100 }
]
});
});
</script>
the web component
<table id="myGrid"> </table>
the code behind (jqGridHandler.ashx)
public class jqGridHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
MyFirstService.Service1Client client = new MyFirstService.Service1Client();
context.Response.Write(client.GetJsonUsers());
}
private DataSet GetUsersFromDB()
{
AccessDataBase reader = new AccessDataBase();
string selectquery = "SELECT * FROM Registration";
return reader.readDB(selectquery);
}
public string GetJsonUsers()
{
return GetJson(GetUsersFromDB());
}
private string GetJson(DataSet dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataTable dtt in dt.Tables)
foreach (DataRow dr in dtt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
public bool IsReusable
{
get
{
return false;
}
}
}
AccessDB.cs
public SqlConnection Connection { get; set; }
public AccessDataBase()
{
Connection = new SqlConnection("Data Source=.;Initial Catalog=NewDB;Integrated Security=True");
}
public DataSet readDB(string selectquery)
{
SqlCommand cmd = new SqlCommand(selectquery);
using (Connection)
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = Connection;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
and add
using System.Web.Script.Serialization;
and don forget to add the js and css files in the master page.
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="Scripts/JQGrid/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" />
<link href="Scripts/JQGrid/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="Scripts/JQGrid/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="Scripts/JQGrid/jquery.jqGrid.js" type="text/javascript"></script>
<script src="Scripts/JQGrid/grid.locale-en.js" type="text/javascript"></script>
<script src="Scripts/JQGrid/jquery.jqGrid.min.js" type="text/javascript"></script>
I found out the answer by my self here's what i did to implement JQGrid on ASP.net and MySQL database.
ItemCode.ashx
public struct JQGridResults
{
public int page;
public int total;
public int records;
public JQGridRow[] rows;
}
public struct JQGridRow
{
public string ItemCode;
public string PartNumber;
public string ItemDescriptionShort;
public string ItemDescriptionLong;
public string ProductCode;
public string GroupCode;
public string BusinessUnit;
public string[] cell;
}
[Serializable]
public class User
{
public string ItemCode { get; set; }
public string PartNumber { get; set; }
public string ItemDescriptionShort { get; set; }
public string ItemDescriptionLong { get; set; }
public string ProductCode { get; set; }
public string GroupCode { get; set; }
public string BusinessUnit { get; set; }
}
public class ItemCode : IHttpHandler
{
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 = GetUsers(numberOfRows, pageIndex, sortColumnName,sortOrderBy, out totalRecords);
string output = BuildJQGridResults(users, Convert.ToInt32(numberOfRows),Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords));
response.Write(output);
}
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.ItemCode = user.ItemCode;
row.PartNumber = user.PartNumber;
row.ItemDescriptionShort = user.ItemDescriptionShort;
row.ItemDescriptionLong = user.ItemDescriptionLong;
row.ProductCode = user.ProductCode;
row.GroupCode = user.GroupCode;
row.BusinessUnit = user.BusinessUnit;
rows.Add(row);
}
result.rows = rows.ToArray();
result.page = pageIndex;
result.total = (totalRecords + numberOfRows - 1) / 8;
result.records = totalRecords;
JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };
//return new JavaScriptSerializer().Serialize(result);
return serializer.Serialize(result);
}
private Collection<User> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords)
{
Collection<User> users = new Collection<User>();
MySqlConnection conn = Functions.GetConnection();
string sql;
sql = "SELECT * FROM swans.tblsomain,tblligerstatus;";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader data1 = cmd.ExecuteReader();
string connectionString = "server=127.0.0.1;database=swans;uid=root;password=''";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand())
{
command.Connection = connection;
command.CommandText = "select ItemCode,PartNumber,ItemDescriptionShort,ItemDescriptionLong,ProductCode,GroupCode,BusinessUnit from tblitemcodefromqne;";
command.CommandType = CommandType.Text;
MySqlParameter paramPageIndex = new MySqlParameter("#PageIndex",MySqlDbType.Int32);
paramPageIndex.Value = Convert.ToInt32(pageIndex);
command.Parameters.Add(paramPageIndex);
MySqlParameter paramColumnName = new MySqlParameter("#SortColumnName", MySqlDbType.VarChar, 50);
paramColumnName.Value = sortColumnName;
command.Parameters.Add(paramColumnName);
MySqlParameter paramSortorderBy = new MySqlParameter("#SortOrderBy", MySqlDbType.VarChar, 4);
paramSortorderBy.Value = sortOrderBy;
command.Parameters.Add(paramSortorderBy);
MySqlParameter paramNumberOfRows = new MySqlParameter("#NumberOfRows", MySqlDbType.Int32);
paramNumberOfRows.Value = Convert.ToInt32(numberOfRows);
command.Parameters.Add(paramNumberOfRows);
MySqlParameter paramTotalRecords = new MySqlParameter("#TotalRecords",MySqlDbType.Int32);
totalRecords = 0;
paramTotalRecords.Value = totalRecords;
paramTotalRecords.Direction = ParameterDirection.Output;
command.Parameters.Add(paramTotalRecords);
connection.Open();
using (MySqlDataReader dataReader = command.ExecuteReader())
{
User user;
while (dataReader.Read())
{
user = new User();
user.ItemCode = Convert.ToString(dataReader["ItemCode"]);
user.PartNumber = Convert.ToString(dataReader["PartNumber"]);
user.ItemDescriptionShort = Convert.ToString(dataReader["ItemDescriptionShort"]);
user.ItemDescriptionLong =Convert.ToString(dataReader["ItemDescriptionLong"]);
user.ProductCode = Convert.ToString(dataReader["ProductCode"]);
user.GroupCode = Convert.ToString(dataReader["GroupCode"]);
user.BusinessUnit = Convert.ToString(dataReader["BusinessUnit"]);
users.Add(user);
}
}
totalRecords = users.Count;
}
return users;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
ItemCode.aspx
<script type="text/javascript" >
$(function () {
$("#UsersGrid").jqGrid({
type: 'POST',
url: 'ItemCode.ashx',
datatype: "json",
width: 1245,
height: 450,
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "total",
records: "records"
},
colNames: ['Item Code', 'Part Number', 'Short Description', 'Long Description', 'Product Code', 'Group Code', 'Business Unit'],
colModel: [
{ name: 'ItemCode', index: 'ItemCode', width: 60, editable:true, sorttype: 'string' },
{ name: 'PartNumber', index:'PartNumber', width: 50 },
{ name: 'ItemDescriptionShort',index:'ItemDescriptionShort', width: 260 },
{ name: 'ItemDescriptionLong',index:'ItemDescriptionLong', width: 260 },
{ name: 'ProductCode',index:'ProductCode', width: 50 },
{ name: 'GroupCode',index:'GroupCode', width: 50 },
{ name: 'BusinessUnit',index:'BusinessUnit', width: 50 },
],
cmTemplate: { title: false },
rowNum: 20,
mtype: 'GET',
loadonce: true,
rowList: [10, 20, 30],
pager: '#UsersGridPager',
sortname: 'ItemCode',
multiSort: true,
gridview: true,
viewrecords: true,
sortorder: 'asc',
caption: "Item Code Summary"
});
jQuery("#UsersGrid").jqGrid('navGrid', '#UsersGridPager',
{ del: false, add: false, edit: false, search: false });
jQuery("#UsersGrid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false });
});
</script>
</head>
<body>
<form id="UsersForm" runat="server">
<table id="UsersGrid" ></table>
<div id="UsersGridPager"></div>
</form>
</body>

Return count and data as json into extjs grid

How can I return two Json objects? Basically I am trying to send bunch of datas from sql db and the number of rows in the db.
The below code sends myData successfully, but now I would also like to send count.
string sqlquery = "SELECT Q1, Q2, Q3, Q4, Improvements, Comments FROM myTable";
conn.Open();
SqlDataAdapter cmd = new SqlDataAdapter(sqlquery, conn);
SqlCommand comd = new SqlCommand(sqlquery, conn);
DataSet myData = new DataSet();
cmd.Fill(myData, "myTable");
comd.CommandText = "SELECT COUNT(*) FROM myTable";
Int32 count = (Int32)comd.ExecuteScalar();
comd.ExecuteNonQuery();
conn.Close();
return JsonConvert.SerializeObject(myData, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
this is my grid
this.grid = Ext.create('Ext.grid.Panel', {
title: 'GridView App',
frame: true,
trackMouseOver: true,
disableSelection: true,
autoHeight: true,
store: store,
loadMask: true,
columns: [
{ header: 'Q1',
sortable: true, dataIndex: 'Q1'
},
{ header: 'Q2',
sortable: true, dataIndex: 'Q2'
},
{ header: 'Q3',
sortable: true, dataIndex: 'Q3'
},
{ header: 'Q4',
sortable: true, dataIndex: 'Q4'
},
{ header: 'Improvements', flex: 1,
sortable: true, dataIndex: 'Improvements'
},
{ header: 'Comments', flex: 1,
sortable: true, dataIndex: 'Comments'
}
],
and this is my store...
var store = Ext.create('Ext.data.JsonStore', {
storeId: 'myData',
scope: this,
pagesize: itemsPerPage,
remoteSort: true,
fields: [
{ name: 'Q1', type: 'int' },
{ name: 'Q2', type: 'int' },
{ name: 'Q3', type: 'int' },
{ name: 'Q4', type: 'int' },
{ name: 'Q5', type: 'int' },
{ name: 'Improvements', type: 'string' },
{ name: 'Comments', type: 'string' }
],
sorters: [
{
property: 'Q1',
direct: 'ASC'
}
],
proxy: {
type: 'ajax',
scope: this,
url: 'GridView/writeRecord',
reader: {
type: 'json',
root: 'myTable',
totalProperty: 'count'
}
}
});
This is, basically, how i do it in my ASP.NET apps, i'm also using JSON.NET:
string sqlquery = "SELECT Q1, Q2, Q3, Q4, Improvements, Comments FROM myTable";
conn.Open();
SqlDataAdapter cmd = new SqlDataAdapter(sqlquery, conn);
SqlCommand comd = new SqlCommand(sqlquery, conn);
DataSet myData = new DataSet();
cmd.Fill(myData, "myTable");
comd.CommandText = "SELECT COUNT(*) FROM pid_FluSurvey";
Int32 count = (Int32)comd.ExecuteScalar();
comd.ExecuteNonQuery();
conn.Close();
return JsonConvert.SerializeObject( new { myTable = myData.Tables[0], count = count }, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
What is important here is that you can call SerializeObject on any anonymous type and put there any number of propertys you want/need.
here it is how I do, I use it for all my mvc apps. I found this example on the internet(I changed it a little bit), since I am at the office and work only with webforms here(I know... that's bad, when you go mvc you never go back)
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
public class HomeController : Controller
{
public List<Person> personList = new List<Person>{
new Person{ Name="Jpnh", Surname="Coco"},
new Person{ Name="Mike", Surname="Nile"}
};
public ActionResult Index()
{
return View();
}
public ActionResult GetData()
{
return Json(personList);
}
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#button').click(GetValue);
});
function GetValue() {
$.ajax({
url: "/Home/GetData",
success: function (data) {
alert(data[0].Name);
}
});
};
</script>
The code by itself is very intuitive to understand and I am assuming you have no problems filling out a Generic list from database
let me know

Categories