Chart in MVC application for date wise punch In-Out time - c#

I am using visual studio 2019 and developing a MVC application. I want to render a chart between in-time (on Y-Axis) and attendance date (on X-Axis) for employee attendance date wise. I am getting all those data of the employee as an object list. Please refer screenshots. Attendance Date Object List
Punch In-Time Object List
I am using Chart.js (V 3.7.1) in MVC application. I have googled a lot but can't find the solution. I am new to this platform, please help me out to find out the solution to do that? Thanks in advance.
Here is my code of Action Method:
[HttpGet]
public ActionResult BarChart()
{
try
{
List<object> iData = new List<object>();
DataTable dt = new DataTable();
using (OracleConnection con = new OracleConnection(AppSetting.OraConnectionString()))
{
string str = #"SELECT to_char(cast(EAE_DATE as date),'dd-MON-yy') AS EAE_DATE ,to_char(cast(IN_TIME as date),'hh24:mi:ss') AS IN_TIME,to_char(cast(OUT_TIME as date),'hh24:mi:ss') AS OUT_TIME FROM EMPLOYEE_DAILY_ATTENDANCE_EXL WHERE EAE_EM_ID = 904 AND EAE_YEAR=2022 AND EAE_MONTH=11 ORDER BY EAE_DATE";
OracleDataAdapter da = new OracleDataAdapter(str, con);
da.Fill(dt);
foreach (DataColumn dc in dt.Columns)
{
List<object> x = new List<object>();
x = (from DataRow drr in dt.Rows select drr[dc.ColumnName]).ToList();
iData.Add(x);
}
ViewBag.Date_List = iData[0];
ViewBag.InTime_List = iData[1];
ViewBag.OutTime_List = iData[2];
}
return View();
}
catch (Exception)
{
throw;
}
}
And View code is:
#{
ViewBag.Title = "BarChart";
}
<div style="text-align: center">
<canvas id="barcanvas"></canvas>
</div>
<meta name="viewport" content="width=device-width" />
<title>Attendance Punctuality</title>
#* I have installed Chart.js from ManageNugetPackages so not using the cdn *#
<script>
var DayDate =#Html.Raw(Json.Encode(ViewBag.Date_List));
var InTime =#Html.Raw(Json.Encode(ViewBag.InTime_List));
var OutTime =#Html.Raw(Json.Encode(ViewBag.OutTime_List));
var ChartData =
{ labels: DayDate,
datasets: [{
label: 'In Time',
backgroundColor: "#aad2ed",
borderWidth: 2,
data: InTime,
borderColor: '#0062ff',
fill: false,
},
{
label: 'Out Time',
backgroundColor: "#f7bd83",
borderWidth: 2,
data: OutTime,
borderColor: '#F78511',
fill: false,
}]
};
window.onload = function () {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{ type: 'line', //line,pie,bar,doughnut
data: ChartData,
showDatapoints: true,
legend: { position: 'bottom' },
options:
{
title: { display: true, text: "Attendance Trial Graph"},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>

Related

How to bind string in ChartJs in asp.net using C#?

I'm trying to bind object to ChartJS datasets data but it's not appearing and there's no error.
Below is my C# Code:
[WebMethod]
public static List<object> GetChartData()
{
List<object> chartData = new List<object>();
List<string> labels = new List<string>();
List<int> data = new List<int>();
labels.Add("Completed jobs");
data.Add(Convert.ToInt32(90));
labels.Add("Current running jobs");
data.Add(Convert.ToInt32(10));
chartData.Add(labels.ToArray());
chartData.Add(data.ToArray());
return chartData;
}
My Client side code:
function OnSuccess_(reponse) {
var aData = reponse.d;
window.ubdChart = new Chart(t, {
type: "pie",
data: {
datasets: [{
hoverBorderColor: "#ffffff",
data: aData, // Bind int values here
backgroundColor: ["rgba(0,123,255,0.9)", "rgba(0,123,255,0.5)"]
}],
labels: ["Completed jobs", "Current running jobs"] //Bind label values here
},
}
})
};
It's working after changing the code as below.
function OnSuccess_(reponse) {
var aData = reponse.d;
console.log(aData);
window.ubdChart = new Chart(t, {
type: "pie",
data: {
datasets: [{
hoverBorderColor: "#ffffff",
data: aData[1],
backgroundColor: ["rgba(0,123,255,0.9)", "rgba(0,123,255,0.5)"]
}],
labels: aData[0]
},
options: {
legend: {
position: "bottom",
labels: { padding: 25, boxWidth: 20 }
}, cutoutPercentage: 0, tooltips: { custom: !1, mode: "index", position: "nearest" }
}
})
};

How to convert List<string> to JSON for kendo grid

For the data query part, I return data as List<Customer>.
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
custlist = new List<Customer>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Customer cobj = new Customer();
cobj.CustomerID = Convert.ToInt32(ds.Tables[0].Rows[i]["CustomerID"].ToString());
cobj.Name = ds.Tables[0].Rows[i]["Name"].ToString();
cobj.Address = ds.Tables[0].Rows[i]["Address"].ToString();
cobj.Mobileno = ds.Tables[0].Rows[i]["Mobileno"].ToString();
cobj.EmailID = ds.Tables[0].Rows[i]["EmailID"].ToString();
cobj.Birthdate = Convert.ToDateTime(ds.Tables[0].Rows[i]["Birthdate"].ToString());
custlist.Add(cobj);
}
return custlist;
For the API part, the code is as below.
Customer objCustomer = new Customer();
DataAccessLayer objDB = new DataAccessLayer(); //calling class DBdata
// What do I need to do here next for my api to convert List<string> to json Matches kendo grid
// I tried with code but still not working => string jsonString = JsonSerializer.Serialize(objCustomer);
objCustomer.ShowallCustomer = objDB.Selectalldata();
For the Kendo UI part, the code is as below:
<div id="grid"></div>
<script>
$(document).ready(function () {
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/handler.ashx?tbl=like&func=getall", //api call code as above
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
});
$("#grid").kendoGrid({ //kendo grid ui
dataSource: dataSource,
pageable: true,
height: 550,
toolbar: ["create"],
editable: "inline"
});
});
function customBoolEditor(container, options) {
$('<input class="k-checkbox" type="checkbox" name="Discontinued" data-type="boolean" data-bind="checked:Discontinued">').appendTo(container); //Kendo grid custom
}
</script>
Issue: API returns the data list as JSON, but it still doesn't output.
Hope everybody help me. Thanks so much.
I'm assuming you have verified that you have JSON coming to your browser. If not, first make sure you're actually getting the data.
You may have to define the datasource schema for it to work. Take a look at this link for a fully working example that is similar to your code.
transport: {
read: "/api/handler.ashx?tbl=like&func=getall"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
}
If you're looking to generate the schema dynamically, take a look at this link.

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>

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>

MVC: using controller data in view

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")"

Categories