I want to display the club name and the number of children from the table below in a piechart
Here is the behind code for the PieChart webform I have created:
public partial class PieChart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
string club_name;
int no_children;
public int TargetClub_No()
{
string CS = ConfigurationManager.ConnectionStrings["dbyouthworkConnectionString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(CS))
{
MySqlCommand cmd = new MySqlCommand("SELECT no_children, club_name FROM pie_chart WHERE club_name = 'Target Club'", con);
con.Open();
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
club_name = rdr["club_name"].ToString();
no_children = Convert.ToInt32(rdr["no_children"]);
}
return no_children;
}
}
}
I have already downloaded the js.chart file and jquery file
Here is the code in the PieChart.aspx file I have created :
<body>
<form id="form1" runat="server">
<canvas id="mycanvas" width="256" height="256"></canvas>
<script>
$(document).ready(function () {
var ctx = $("#mycanvas").get(0).getContext("2d");
// pie chart data
var t = <% TargetClub_No(); %>;
var data = [
{
value: t,
color: "cornflowerblue",
highlight: "lightskyblue",
label: "Target Club"
},
{
value: 50,
color: "lightgreen",
highlight: "yellowgreen",
label: "Lightgreen"
},
{
value: 40,
color: "orange",
highlight: "darkorange",
label: "Orange"
}
];
//draw
var piechart = new Chart(ctx).Pie(data);
});
</script>
<div>
</div>
</form>
*Here I have firstly tried to input the number of children from target club however when I run the code I get a blank page instead of a pie chart
SCREEN SHOTS USING DEV TOOLS IN CHROME:
This one shows that I have done something wrong in calling 'public int TargetClub_No()'
Here is the screen shot of the networks tab:
Not sure what this tab means though...
First there are syntax errors in your JS..
This portion:
var t = '<% TargetClub_No(); %>'
//var data = [
should look like this:
var t = <%= TargetClub_No() %>;
var data = [
Now your C# method TargetClub_No() needs to return a value to assign to t.
For what you are trying to do at first you want to return the number of children from target club. Like this:
public int TargetClub_No()
{
...
//nothing else needs to change
...
return no_children;
}
Eventually you will probably want your method TargetClub_No() to return all of the data in a way that you can assign it to data directly.
Here is an article that does exactly what you want (and a little more):
Chart.js Asp.net : Create Pie chart with database jQuery Ajax C#
Related
I am a beginner when it comes to the following technologies:
- ASP.NET MVC
- Entity Framework
- JavaScript (in this instance, CanvasJS)
I am trying to render a chart based on a Data Model that I have created in my solution. I am following the tutorial here (adapted to my own purposes) https://canvasjs.com/docs/charts/integration/asp-net-mvc-charts/how-to/asp-net-mvc-charts-data-entity-database/ and I have completed the following.
Created a Model of my data via EF
Passed that data from my Controller to my View
Attempted to render the chart in the View CSHTML
However, the chart does not render. When I use Chrome Debugging, the Javascript shows that the 'result' is my strongly typed model, but this must be incorrect as the error is Uncaught SyntaxError: Unexpected end of input
The rendered Javascript is as follows:
<h2>StoreView - Testing this for store group P777S001</h2>
<hr />
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<div class="text-info">Here are some examples of sales data via Entity Framework</div>
</div>
<div class="col-md-6">
<div id="chartContainer"></div>
</div>
</div>
</div>
<script type="text/javascript">
var result = System.Collections.Generic.List`1[InSiteDashboard.Models.InSiteStoreSalesSummaryTable];
var datapoints = [];
for (var i = 0; i < result.length; i++) {
datapoints.push({ label: result[i].x, y: result[i].y });
}
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
zoomEnabled: true,
animationEnabled: true,
title: { text: "Line chart" },
data: [{
type: "line",
dataPoints: dataPoints,
}]
});
chart.render();
});
</script>
I am passing this to the View using the following code (it's prototyping so the code is messy apologies)
Controller:
string _servername = $"P{store}S001";
var sales = insite.InSiteStoreSalesSummaryTables.Where(s => s.ServerName == _servername && s.daily_sales_figure > 0);
//var storeEntries = db.StoreSystemInformations.Where(s => s.StoreNumber == store);
if (sales == null)
{
return HttpNotFound();
}
ViewBag.TestValue = $"Testing this for store group {_servername}";
return View(sales.ToList());
Can anyone see something I'm obviously doing wrong here?
From first glance, I assumed your problem seem occurred because of this line:
var result = System.Collections.Generic.List`1[InSiteDashboard.Models.InSiteStoreSalesSummaryTable];
I think you're passing list directly to a JS definition intended to create JS array, but Razor returns fully-qualified name of the List<InSiteDashboard.Models.InSiteStoreSalesSummaryTable> collection because Razor implicitly called ToString() in the view instead of iterating it.
Since List``1[InSiteDashboard.Models.InSiteStoreSalesSummaryTable] is not recognized as a JS identifier or property, then "Unexpected end of input" message was thrown because of invalid syntax.
You could use model serialization to pass List<T> collection as JS array, as in example below (assumed you have model directive with #model IEnumerable<InSiteStoreSalesSummaryTable> or #model List<InSiteStoreSalesSummaryTable> as implied by return View(sales.ToList())):
// standard way
var result = JSON.parse('#Html.Raw(Json.Encode(Model))');
// using Newtonsoft.Json library
var result = JSON.parse('#Html.Raw(JsonConvert.SerializeObject(Model))');
Here is an example implementation of the script:
#model IEnumerable<InSiteStoreSalesSummaryTable>
<!-- other HTML elements, skipped for brevity -->
<script>
var result = JSON.parse('#Html.Raw(Json.Encode(Model))');
var datapoints = [];
for (var i = 0; i < result.length; i++) {
datapoints.push({ label: result[i].x, y: result[i].y });
}
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
zoomEnabled: true,
animationEnabled: true,
title: { text: "Line chart" },
data: [{
type: "line",
dataPoints: dataPoints,
}]
});
chart.render();
});
</script>
I'm developing part of application in which i need to generate reports on some user athletes and preview on chart following:
dates and number of exposures to certain lift
Here is the html and javascript:
<div class="chart" id="bar-chart-#exposureReport.AthleteId" style="height: 300px; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
<script>
drawChart('#exposureReport.CoachId', '#exposureReport.AthleteId');
function drawChart(coachId, athleteId) {
//debugger;
$.getJSON('#Url.Action("FetchAthleteChartData", "Reports")?coachId=' + coachId + '&athleteId=' + athleteId,
function (data) {
var datax = JSON.stringify(data);
alert(datax);
Morris.Bar({
element: 'bar-chart-' + athleteId,
resize: true,
barSizeRatio: 0.12,
barGap: 3,
data: $.parseJSON(datax),
barColors: ['#ff0000'],
xkey: ['exposures'],
ykeys: ['dates'],
labels: ['Times exposed'],
hideHover: 'auto'
});
}
);
}
</script>
</div>
I foreach all the reports i have on current view and preview them. I want to show a chart for each report.
I call the javascript function and pass the coachId and athleteId values and let server fetch the data for me:
[HttpGet]
public JsonResult FetchAthleteChartData(string coachId, string athleteId)
{
var exerciseReport =
_applicationUserOperations.GetAllExposureReportsForCoachByAthleteId(coachId, athleteId);
var filteredDates = exerciseReport.Exposures.Select(x => x.ExposureDate).ToList();
var filteredExposures = exerciseReport.Exposures.Select(x => x.NumberOfLifts).ToList();
var result = new
{
Dates = filteredDates,
Exposures = filteredExposures
};
return Json(result);
}
When my alert(datax) triggers it shows (I have only one training/exercise/lift entry atm):
{"dates":["2018-06-01T00:00:00"],"exposures":[5]}
Is this correct format to parse ? How do I parse it so the chart data can understand it and display it.
I know this is a duplicate question but I tried all the previous answers. Not working for me. So I give here my code. When try to load more than 2000 record I got this error.
"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set
on the maxJsonLength property."
In Controller
public ActionResult Index(SearchFilter sf)
{
Model m = new Model();
IList<Info> Details;
IList<rViewModel> RLst = new List<rViewModel>();
using (var db = new con())
{
RLst = (from p in Details
select new rViewModel
{
Id=p.Id,
Description = p.Description,
Remark = p.Remark,
}).ToList();
m.Result = RLst;
}
return View(m);
}
In View,
$(document).ready(function () {
$('#Product').dataTable({
"columnDefs": [
{ "width": "20%", "targets": 0, "orderable": true, },
{ "width": "40%", "targets": 1,"orderable": true, },
{ "width": "40%", "targets": 2,"orderable": true, },
],"oLanguage": {"sSearch": "Filter:"}
});
var t = $('#Product').DataTable();
t.clear();t.draw();
var model =#Html.Raw(Json.Encode(Model.Result));
if(model!=null && model.length>0 )
{
AddData(model);
}
$('#Id').focus();
});
Result Model is actually a partial view.
On the line in view,
var model =#Html.Raw(Json.Encode(Model.Result));
I got this error. Error image attached below
How to fix?
I tried adding
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"/>
</webServices>
</scripting>
</system.web.extensions>
in web.config already its not working.stuck in this for more than 2 days.. Kindly help..
Thank you mr.Tetsuya Yamamoto for your reference. So far I tried all the link. But as per your link I tried the coding below.
In view
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var jsonModel = serializer.Serialize(Model.Result);
}
and at the line where I got error,I changed my one
var model =#Html.Raw(Json.Encode(Model.Result));
into the line as below:
var model =#Html.Raw(jsonModel);
Previously also I tried these coding, but wrongly entered in controller. From your link only I find out need to put in view. This will help some one whose web.config declaration is not working.
Link Courtesy(once again) as follows: Json Encode throwing exception json length exceeded
"jsonSerialization maxJsonLength" did not work for me on this problem
But I reference #Halim answer.
This also works for me:
previous code with the problem:
<script>
$(document).ready(function () {
modelname(#Html.Raw(Json.Encode(Model)));
});
</script>
code resolution:
<script>
$(document).ready(function () {
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var jsonModel = serializer.Serialize(Model);
modelname(jsonModel)
});
</script>
I have a view with some javascript code for a pie chart in it. This view has an action method, where I am running some queries an converting the results to json in order to fill the pie chart with something.
The problem is that I don't know (and couldn't understand from another questions here) how to properly return a json from action to view and actually work with the data in some way in the view.
Currently, what I have give me a json string in my browser instead of a view.
I do not have a model in my project for the data that's in in the json.
Here's all the code from my view :
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['German', 5.85],
['French', 1.66],
['Italian', 0.316],
['Romansh', 0.0791]
]);
var options = {
legend: 'none',
pieSliceText: 'label',
title: 'Accumulated experience',
pieStartAngle: 100,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<div id="piechart" style="width: 1000px; height: 600px;"></div>
And here is my controller :
public ActionResult experiencePieChart()
{
//some queries
var json = JsonConvert.SerializeObject(perclist);
return Json(json, JsonRequestBehavior.AllowGet);
}
your controller method should return JsonResult, just change it's signature in following way:
public JsonResult experiencePieChart()
{
var perclist = ...
//some queries
return Json(perclist, JsonRequestBehavior.AllowGet);
}
then in your js code you could call it
$(document).ready(function()
{
$.get("/YourController/experiencePieChart",ShowPieChart,"json").fail(ShowPieChartFail);
});
of course then you need define ShowPieChart function which will render that graph
function ShowPieChart(chartData){
// this code will be executed after result is returned asynchronously
// chartData contains JSON representation of perclist variable
}
In case you'd like to do that data-transfer just on each refresh of page, you could store data required for chart. In your .cshtml you'd just add
<script type="text/javascript">
var ChartData = #Html.Raw(Json.Encode(#Model.MyData))
</script>
then during execution of js on client side you'd have ChartData variable initialized. Anyway this way have multiple downside and is not scalable at all. Going with ajax call seems much better to me.
I have researched and tried everything that I can think of to try and retrieve the actual values for the Iteration, Project, and User columns but I can never get the column data to populate for those like the name of the iteration, name of the project, and name of the submitted by user. I have read that it should be fine to do in the fetch the way I have it and others have said that you have to specify the types with something like this
types : ['defect','user','iteration','project'],
When I do that I dont ever load my grid. I have tried things like this as recommended by some
defect.Iteration.Name
OR
Iteration.Name
I could really use some help here. I also read one article saying the WSAPI no longer supports this kind of request and has to be handled in multiple queries/fetches. Anywho, here is the code that I am using...
function onLoad() {
var rallyDataSource = new rally.sdk.data.RallyDataSource(
'__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
var config = {
type : 'defect',
key : 'defects',
columnKeys : ["FormattedID", "Name", "Priority125", "Iteration", "Project", "SubmittedBy", "CreationDate", "ScheduleState", "State"],
fetch : 'FormattedID,Name,Priority125,Iteration,Project,SubmittedBy,CreationDate,ScheduleState,State',
query : '((State != "Closed") OR (ScheduleState != "Accepted"))',
order : 'Priority125'
};
var table = new rally.sdk.ui.Table(config, rallyDataSource);
table.display("tableDiv");
}
rally.addOnLoad(onLoad);
There are several things needed in order to get this to work as you're wanting:
You can fetch recursively up to a level of one deep. Thus if you want to grab a Defect's Name, Formatted ID, and the Project Name, your fetch would look like:
fetch: "Name,FormattedID,Project,Name"
Grab the data via rallyDataSource.findAll()
Post-process the data so that you feed your table all string data. I.e. clobber Object Reference fields like Project, with the Project Name instead.
Finally, populate and display the table.
Here's working example that illustrates what I think you're wanting to do (minus the "Priority 125" custom field that you have defined).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Copyright (c) 2011 Rally Software Development Corp. All rights reserved -->
<html>
<head>
<title>Defect Information</title>
<meta name="Name" content="Defect Information" />
<meta name="Version" content="1.32" />
<meta name="Vendor" content="Rally Software" />
<script type="text/javascript" src="https://rally1.rallydev.com/apps/1.32/sdk.js?debug=True"></script>
<script type="text/javascript">
var rallyDataSource = null;
var table = null;
function showTable(results) {
if (table) {
table.destroy();
}
var tableConfig = {
columnKeys : ["FormattedID", "Name", "Iteration", "Project", "SubmittedBy", "CreationDate", "ScheduleState", "State"],
columnWidths : ["85px", "350px", "90px", "100px", "100px", "120px", "100px", "100px" ]
};
table = new rally.sdk.ui.Table(tableConfig);
// Loop through the rows and clobber object attributes of the results collection with
// string values
for(var i = 0; i < results.defects.length; i++){
thisDefect = results.defects[i];
var iterationName = "";
// Grab value fields
if (thisDefect.Iteration != null) {
iterationName = results.defects[i].Iteration.Name;
} else {
iterationName = "Un-scheduled";
}
var projectName = thisDefect.Project.Name;
// Re-map SubmittedBy object to SubmittedBy string
submittedByDisplayName = thisDefect.SubmittedBy === null ? "": thisDefect.SubmittedBy._refObjectName;
// Clober objects with values
results.defects[i].Iteration = iterationName;
results.defects[i].Project = projectName;
results.defects[i].SubmittedBy = submittedByDisplayName;
}
table.addRows(results.defects);
table.display(document.getElementById('defectsDiv'));
}
function onLoad() {
rallyDataSource = new rally.sdk.data.RallyDataSource(
'__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
var config = {
type : 'defect',
key : 'defects',
fetch: 'FormattedID,Name,SubmittedBy,Iteration,Name,Project,Name,CreationDate,ScheduleState,State',
query : '((State != "Closed") OR (ScheduleState != "Accepted"))',
};
rallyDataSource.findAll(config, showTable);
rallyDataSource.setApiVersion("1.38");
}
rally.addOnLoad(onLoad);
</script>
</head>
<body>
<div id="aDiv"></div>
<div style="font-weight: bold;"><p>Defects</p></div>
<div id="defectsDiv"></div>
</body>
</html>