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>
Related
i have a razor project where i implemented DataTables. I'm trying to retrieve data from the database dynamically with ajax in this way:
$('#orariDipendenti').DataTable({
'orderMulti': false,
'stateSave': true,
'paging': true,
'pageLength': 10,
'filter': false,
'processing': true,
'serverSide': true,
'ajax': {
url: '?handler=LoadData',
type: 'POST',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
},
});
my back code is this:
public JsonResult LoadTable()
{
try
{
var idDipendente = HttpContext.Session.GetInt32("IdDipendente");
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
int pagesize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordstotal = 0;
var recordData = context.Pres_Orari.Where(x => x.IdDipendente == idDipendente).ToList();
recordstotal = recordData.Count;
var data = recordData.Skip(skip).Take(pagesize).ToList();
return new JsonResult(new { draw = draw, recordsFiltered = recordstotal, recordsTotal = recordstotal, data = data });
}
catch (Exception)
{
throw;
}
}
the error i get when i open the page is this:
DataTables warning: table id={id} - Invalid JSON response.
I know the broblem is with the returned json but i don't know where. somebody can help me?
Firstly,your handler name is LoadTable,your url in ajax is url: '?handler=LoadData'.You need to change url to url: '?handler=LoadTable'.And here is a working demo(I also change xhr.setRequestHeader("XSRF-TOKEN" to xhr.setRequestHeader("RequestVerificationToken",if your code can work,you don't need to changexhr.setRequestHeader("XSRF-TOKEN"):
cshtml:
#Html.AntiForgeryToken()
<table id="orariDipendenti" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr class="table-info">
<th>IdDipendente</th>
<th>Name</th>
</tr>
</thead>
</table>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script>
<script>
$(function () {
$('#orariDipendenti').DataTable({
'orderMulti': false,
'stateSave': true,
'paging': true,
'pageLength': 10,
'filter': false,
'processing': true,
'serverSide': true,
ajax: {
url: '?handler=LoadTable',
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
},
columns: [
{ data: 'idDipendente' },
{ data: 'name' },
]
});
});
</script>
Model:
public class MyModel1 {
public int IdDipendente { get; set; }
public string Name { get; set; }
}
cshtml.cs(I use fake data to test):
public static List<MyModel1> list = new List<MyModel1> { new MyModel1 { IdDipendente = 1, Name = "name1" }, new MyModel1 { IdDipendente = 2, Name = "name2" }, new MyModel1 { IdDipendente = 3, Name = "name3" } };
public JsonResult OnPostLoadTable()
{
try
{
var idDipendente = 1;
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
int pagesize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordstotal = 0;
var recordData = list.Where(x => x.IdDipendente==idDipendente).ToList();
recordstotal = recordData.Count;
var data = recordData.Skip(skip).Take(pagesize).ToList();
return new JsonResult(new { draw = draw, recordsFiltered = recordstotal, recordsTotal = recordstotal, data = data });
}
catch (Exception)
{
throw;
}
}
}
result:
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>
<---- 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; }
}
Hi i have DataTable which is binding to Gridview. But in need to bind that know to jqxgrid or jqxdatatable. After googling so many times i didn't got proper solution for this.
DataTable tb1= qry.GetTicketDetails();
serviceWindow.DataSource = tb;
serviceWindow.DataBind();
This what i'm doing actully now.
IN jquery i can take XML shown in below.
var source =
{
dataType: "json",
dataFields: [
{ name: 'name', type: 'string' },
{ name: 'type', type: 'string' },
{ name: 'calories', type: 'int' },
{ name: 'totalfat', type: 'string' },
{ name: 'protein', type: 'string' }
],
id: 'id',
url: "data/ticket.XML", //how to take datatable from code behind file
};
.aspx code -->>
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestCellSelection.aspx.cs" Inherits="CourierApp.Project.TestCellSelection" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title id='Description'></title>
<link rel="stylesheet" href="../JQWidgets/jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="../JQWidgets/scripts/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxmenu.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.selection.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.columnsresize.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../JQWidgets/scripts/demos.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxlistbox.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxdropdownlist.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.pager.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.edit.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxnumberinput.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxpanel.js"></script>
<script type="text/javascript" src="../JQWidgets/jqwidgets/jqxgrid.sort.js"></script>
<script type="text/javascript">
$(document).load(function () {
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#button").jqxButton({
theme: 'energyblue',
height: 30
});
$("#button").click(function () {
var cells = $('#jqxgrid').jqxGrid('getselectedcells');
var cellInfo = "";
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cellInfo += "\nRow: " + cell.rowindex + ", " + cell.datafield;
}
alert(cellInfo);
});
//GetData
var data = {};
var dataFelds = {};
var dataCols = {};
GetDatas();
GetCol_Datafeilds();
GetCol_Columns();
function GetDatas() {
$.ajax({
url: '<%=ResolveUrl("~/Project/Service.aspx/GridValues")%>',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (dataa) {
var response = dataa.d;
if (response != "Error") {
data = response;
console.log(data);
}
else {
alert("Retrive Error !!");
}
},
failure: function (data) {
alert(response.d);
},
error: function (error) {
console.log("Error : " + error.responseText);
}
});
}
function GetCol_Datafeilds() {
$.ajax({
url: '<%=ResolveUrl("~/Project/Service.aspx/Col_Datafeilds")%>',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (dataa) {
var response = dataa.d;
if (response != "Error") {
dataFelds = $.parseJSON(response);
console.log(dataFelds);
}
else {
alert("Retrive Error !!");
}
},
failure: function (data) {
alert(response.d);
},
error: function (error) {
console.log("Error : " + error.responseText);
}
});
}
function GetCol_Columns() {
$.ajax({
url: '<%=ResolveUrl("~/Project/Service.aspx/Col_Columns")%>',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (dataa) {
var response = dataa.d;
if (response != "Error") {
dataCols = $.parseJSON(response);
console.log(dataCols);
}
else {
alert("Retrive Error !!");
}
},
failure: function (data) {
alert(response.d);
},
error: function (error) {
console.log("Error : " + error.responseText);
}
});
}
// prepare the data
var source =
{
datatype: "json",
datafields: dataFelds,
updaterow: function (rowid, rowdata, commit) {
// synchronize with the server - send update command
// call commit with parameter true if the synchronization with the server is successful
// and with parameter false if the synchronization failder.
commit(true);
},
localdata: data
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
width: 1000,
source: dataAdapter,
editable: true,
selectionmode: 'multiplecellsadvanced',
columnsresize: true,
columns: dataCols
});
// $('#jqxgrid').jqxGrid('pincolumn', 'From_KG');
//$("#jqxgrid").jqxGrid('enablehover', event.args.checked);
});
<%--$("#<%=btn_SelectCells.ClientID%>").click(function () {
var cells = $('#jqxgrid').jqxGrid('getselectedcells');
var cellInfo = "";
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cellInfo += "\nRow: " + cell.rowindex + ", " + cell.datafield;
}
alert(cellInfo);
});--%>
</script>
</head>
<body class='default'>
<form id="form1" runat="server">
<div>
<div id='jqxWidget'>
<div id="jqxgrid">
</div>
</div>
<div style="margin-top: 10px;">
<input id="button" type="button" value="Get the selected cells" />
<%--<asp:Button ID="btn_SelectCells" runat="server" Text="Get the selected cells" UseSubmitBehavior="False" />--%>
</div>
</div>
</form>
</body>
</html>
.aspx.cs or Web Service Code ----->>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Web.Script.Serialization;
using System.Web.Helpers;
using BL;
using DAL;
using Newtonsoft.Json;
public partial class Project_Service : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region Testing
[WebMethod]
public static String GridValues()
{
String Qry = "SELECT [From Kgs] as From_Kg,[To kgs] as To_Kg,[1] as Zone1,[2] as Zone2,[3] as Zone3,[4] as Zone4,[5] as Zone5,[6] as Zone6,[7] as Zone7,[8] as Zone8,[9] as Zone9 FROM Tnt_Rate";
DataTable dt = DbAccess.FetchDatatable(Qry);
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;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
String Val = serializer.Serialize(rows);
if (Val != "")
{
return (Val);
}
else
{
return "Error";
}
}
[WebMethod]
public static String Col_Datafeilds()
{
String Qry = "SELECT [From Kgs] as From_Kg,[To kgs] as To_Kg,[1] as Zone1,[2] as Zone2,[3] as Zone3,[4] as Zone4,[5] as Zone5,[6] as Zone6,[7] as Zone7,[8] as Zone8,[9] as Zone9 FROM Tnt_Rate";
DataTable dt = DbAccess.FetchDatatable(Qry);
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 = new Dictionary<string, object>();
String Col = "";
int counter = 0;
foreach (DataColumn col in dt.Columns)
{
if (counter < 2)
{
row = new Dictionary<string, object>();
row.Add("name", col.ColumnName);
row.Add("type", "string");
rows.Add(row);
}
else if (counter >= 2)
{
row = new Dictionary<string, object>();
row.Add("name", col.ColumnName);
row.Add("type", "number");
rows.Add(row);
}
counter += 1;
}
Col = serializer.Serialize(rows);
//Col = JsonConvert.SerializeObject(rows);
if (Col != "")
{
return (Col);
}
else
{
return "Error";
}
}
[WebMethod]
public static String Col_Columns()
{
String Qry = "SELECT [From Kgs] as From_Kg,[To kgs] as To_Kg,[1] as Zone1,[2] as Zone2,[3] as Zone3,[4] as Zone4,[5] as Zone5,[6] as Zone6,[7] as Zone7,[8] as Zone8,[9] as Zone9 FROM Tnt_Rate";
DataTable dt = DbAccess.FetchDatatable(Qry);
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;
String Col = "";
int counter = 0;
foreach (DataColumn col in dt.Columns)
{
if (counter < 2)
{
row = new Dictionary<string, object>();
row.Add("text", col.ColumnName.ToUpper());
row.Add("datafield", col.ColumnName);
row.Add("columntype", "textbox");
row.Add("width", "100");
row.Add("cellsalign", "left");
//row.Add("pinned", "true");
rows.Add(row);
}
else if (counter >= 2)
{
row = new Dictionary<string, object>();
row.Add("text", col.ColumnName.ToUpper());
row.Add("datafield", col.ColumnName);
row.Add("columntype", "textbox");
row.Add("width", "25");
row.Add("cellsalign", "right");
rows.Add(row);
}
}
Col = serializer.Serialize(rows);
// Col = JsonConvert.SerializeObject(rows);
if (Col != "")
{
return (Col);
}
else
{
return "Error";
}
}
#endregion
}
Paste it ......
Replace the Query by your Query.....
Donot Supply Datafeild and Column Def. in the .aspx page
It's Fully Dynamic Solution !!!
I want to show data which is found in a specific date range according to user inputs startdate and enddate in a chart by using MVC. To achieve this, I need json data.
I can get json data according to user input but the chart cannot be seen because I could not use url:Machines/Parameter.
index.cshtml
<body>
#using (Html.BeginForm("Parameter", "Machines", FormMethod.Post))
{
<div>
Start Date: <input type="datetime" id="start" name="start" />
End Date: <input type="datetime" id="end" name="end" />
</div>
<input type="submit" value="OK" />
Html.EndForm();}
MachinesController.cs
public ActionResult Index()
{
return View();
}
public ActionResult Parameter(DateTime start, DateTime end)
{
MachinesSql a = new MachinesSql();
var data = Json(a.SqlAccessParameter(start, end), JsonRequestBehavior.AllowGet);
return View(data);
}
MODEL:Machines.cs
namespace DenemeReport.Models
{
public class Machines
{
[Key]
public int AutoKey;
public string MachineGroup;
public DateTime StartDate;
public DateTime EndDate;
public int Duration;
}
public class MachinesDBContext : DbContext
{
public DbSet<Machines> Machine { get; set; }
}
public List<Machines> SqlAccessParameter(DateTime startDate, DateTime endDate)
{
SqlConnection myConnection = new SqlConnection(connstr);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("DateRange",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("#SP_startDate", SqlDbType.DateTime).Value =startDate;
myCommand.Parameters.Add("#SP_endDate", SqlDbType.DateTime).Value = endDate;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
myCommand.ExecuteNonQuery();
dataAdapter.SelectCommand = myCommand;
DataSet dSet = new DataSet();
dataAdapter.Fill(dSet);
myConnection.Close();
List<Machines> machinePost = new List<Machines>();
foreach (DataRow row in dSet.Tables[0].Rows)
{
Machines mac = new Machines();
mac.AutoKey = (int)row["AUTOKEY"];
mac.MachineGroup = (string)row["MACHINEGROUP"];
mac.Duration = (int)row["DURATION"];
mac.StartDate = (DateTime)row["STARTTIME"];
mac.EndDate = (DateTime)row["ENDTIME"];
machinePost.Add(mac);
}
return machinePost;
}
Parameter.cshtml (View for Parameter Action which contains chart info)
<title>Intro</title>
<script src="~/Scripts/jquery-1.8.3.min.js"></script>
<script src="~/Scripts/kendo/kendo.all.min.js"></script>
<link href="~/Scripts/kendo/kendo.common.min.css" rel="stylesheet" />
<link href="~/Scripts/kendo/kendo.default.min.css" rel="stylesheet" />
</head>
<div id="chart"></div>
<div id="chart2"></div>
<body>
<script>
$("#chart").kendoChart
({
theme: $(document).data("kendoSkin") || "default",
title: {
text: "Pie Chart Test"
},
legend: {
position: "bottom",
},
dataSource:
{
transport:
{
read:
{
url: "Machines/Parameter", // This part create the problem I think. The url does not work.
dataType: "json",
contentType: 'application/json; charset=utf-8'
}
}
},
seriesDefaults: {
labels: {
visible: true,
format: "{0}"
}
},
series: [{
type: "pie",
field: "Duration",
categoryField: "MachineGroup"
}],
tooltip: {
visible: true,
format: "{0}"
}
});
</script>
</body>
Assuming you're using Razor syntax, replace "Machines/Parameter" by "#Url.Action("Parameter", "Machines")"