Display bar graphs using ASP.NET MVC - c#

I wrote a code to show data from DB in a table view. How can I show same data in Bar graph instead?
This my action method (Updated):
public ActionResult DataFromDataBase()
{
var mostRecentMonday = DateTime.Now.AddDays(-7).StartOfWeek(DayOfWeek.Monday);
var weekEnd = mostRecentMonday.AddDays(7).AddSeconds(-1); //will return the end of the day on Sunday
ViewBag.Monday = mostRecentMonday;
ViewBag.lastWeekSunday = weekEnd;
try
{
Formatting _jsonSetting = default;
ViewBag.DataPoints = JsonConvert.SerializeObject(db.Chats.Where(x => System.Data.Entity.DbFunctions.TruncateTime(x.MSTChatCreatedDateTime) >= mostRecentMonday
&& System.Data.Entity.DbFunctions.TruncateTime(x.MSTChatCreatedDateTime) <= weekEnd).GroupBy(a => System.Data.Entity.DbFunctions.TruncateTime(a.MSTChatCreatedDateTime)).Select(b => new ReportVM()
{
CreatdDate = b.Key,
ChatCountCreatdDate = b.Count()
}).ToList(), _jsonSetting);
return View();
}
catch (System.Data.Entity.Core.EntityException)
{
return View("Error");
}
catch (System.Data.SqlClient.SqlException)
{
return View("Error");
}
}
View to display Graphs
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer"></div>
<script type="text/javascript">
var result = #Html.Raw(ViewBag.DataPoints);
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 with Data-Points from DataBase"
},
data: [
{
type: "column",
dataPoints: dataPoints,
}
]
});
chart.render();
});
</script>
No successs. Used js library to display Graphs, but nothing is working for me. Can some one please help?

Go through below link to explore bar chart on chartjs, its free and easy to use charts,
you just have to specify proper data objects
Check below Example
https://www.chartjs.org/docs/latest/charts/bar.html

Related

Invoke kendo grid create action method to a newly inserted row from javascript

I have an autocomplete and a grid where my intention is to push records from Autocomplete into the grid and save those records using grid's create action from there by invoking a method set in a custom button. Please look at the attached picture to get a clear idea of what my setup looks like.
My saveTerminalRow function doesn't work as expected. Please help.
<div>
#(Html.Kendo().AutoComplete()
.Name("terminalsAutoComplete")
.DataTextField("cmp_name")
// omitted for brevity
.Events(e => e.Select("onTerminalNameSelect"))
)
</div>
<div>
#(Html.Kendo()
.Grid<ProjectName.TerminalOutOfState>()
.Name("manageTOSSqlRecordsGrid")
.Columns(columns =>
{
columns.Bound(c => c.TerminalOutOfStateID).Hidden();
columns.Bound(c => c.TerminalCompanyID).Title("Terminal ID").Width(60);
columns.Bound(c => c.CompanyID).Title("Region").ClientTemplate("#=CompanyName#").Width(40);
columns.Command(cmd =>
{
cmd.Edit();
cmd.Destroy();
cmd.Custom("Save").Visible("showSaveCommand").Click("saveTerminalRow");
}).Title("Action").Width(80);
})
.ToolBar(tbr =>
{
tbr.Create();
tbr.Custom().Text("Load the table");
})
.Editable(edt => edt.Mode(GridEditMode.PopUp).TemplateName("TOoSTemplate").CreateAt(GridInsertRowPosition.Top))
.DataSource(dataSrc => dataSrc
.Ajax()
.ServerOperation(true)
.PageSize(15)
.Model(mdl => mdl.Id(column => column.TerminalOutOfStateID))
.Create(update => update.Action("UpsertTerminalOoSRecordAsync", "Configuration"))
//omitted for brevity
)
.AutoBind(false)
)
</div>
My scripts are like follows:
<script>
//This will add the data from autocomplete into the grid.
function onTerminalNameSelect(e) {
var dataItem = this.dataItem(e.item);
var terminalData = {
TerminalOutOfStateID: 0,
TerminalCompanyID: dataItem.cmp_id,
CompanyID: dataItem.region_id,
CompanyName: dataItem.region_name
};
var grid = $("#manageTOSSqlRecordsGrid").data("kendoGrid");
grid.dataSource.add(terminalData);
}
//This is used to hide and show "Save" button to those rows that are not yet saved to Db.
function showSaveCommand(dataItem) {
// show the Save button for the item with TerminalOutOfStateID =0
if (dataItem.TerminalOutOfStateID == 0) {
return true;
}
else {
return false;
}
}
//This is the method to save the inserted row into Db by calling the create action method. But this doesn't work:
function saveTerminalRow(e) {
var terminalData = this.dataItem($(e.currentTarget).closest("tr"));
var grid = $("#manageTOSSqlRecordsGrid").data("kendoGrid");
grid.saveRow();
}
</script>
Also please advise on how to hide the save button next to unsaved rows after the save operation succeeds.
Well, I can answer my own question now.
This is how I ended up solving this problem:
function saveTerminalRow(e) {
var terminalData = this.dataItem($(e.currentTarget).closest("tr"));
var saveButton = $(e.currentTarget).closest("tr td a.k-grid-Save");
$.ajax({
type: "POST",
url: "#Url.Action("AddTerminalOoSRecordAsync", "Configuration")",
contentType: "application/json",
data: JSON.stringify(terminalData),
success: function (result) {
var title = "", content = "";
if (result[0].TerminalOutOfStateID != undefined && result[0].TerminalOutOfStateID > 0) {
if (!result[0].IsAlreadyInDb) {
title = "Save Success";
content = "New record has been saved.";
}
else {
title = "No new row inserted";
content = "This terminal already exists in Db.";
}
} else {
title = "Save Failed";
content = "Record is not saved.";
}
$("<div></div>").kendoDialog({
closable: false, // hide X
title: title,
content: content,
actions: [{
text: "OK",
action: function (e) {
if (result[0].TerminalOutOfStateID != undefined && result[0].TerminalOutOfStateID > 0) {
saveButton.remove();
}
return true;
},
primary: true
}]
}).data("kendoDialog").open().center();
},
error: function (request, error) {
alert("Record Saving failed.");
}
});
}

ASP.NET MVC: Bar Chart from JSON Data ViewBag

I have a JSON data from database like below to build a dashboard in dashboard ASP.NET MVC. I would like to draw a daily and monthly bar chart with x-axis as datetime (Day) and y-axis as count of activities in a day.
JSON Data:
[{"count":42,"datetime":"2020-07-18T00:00:00"},{"count":49,"datetime":"2020-07-16T00:00:00"},{"count":90,"datetime":"2020-07-14T00:00:00"},{"count":85,"datetime":"2020-07-17T00:00:00"},{"count":100,"datetime":"2020-07-13T00:00:00"},{"count":38,"datetime":"2020-07-19T00:00:00"},{"count":53,"datetime":"2020-07-15T00:00:00"}]
and i want something like this
I've tried the following javascript code but can't. JSON data obtained from ViewBag.dataItems
<script type="text/javascript" >
window.onload = function () {
var result = #Html.Raw(ViewBag.dataItems);
var DataItem =[];
for (var i = 0; i < result.length; i++){
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
data: [{
type: "column",
DataItem: DataItem
}]
});
chart.render();
};
</script>
ThankYou
As I referred to some samples from https://canvasjs.com/docs/charts/chart-types/html5-column-chart/, they used dataPoints property instead of DataItem.
Here is a sample following your data. Hope to help, my friend :))
1. Controllers
public ActionResult Add()
{
ViewData["data"] = #"[{'count':42,'datetime':'2020-07-18T00:00:00'},{'count':49,'datetime':'2020-07-16T00:00:00'},{'count':90,'datetime':'2020-07-14T00:00:00'},{'count':85,'datetime':'2020-07-17T00:00:00'},{'count':100,'datetime':'2020-07-13T00:00:00'},{'count':38,'datetime':'2020-07-19T00:00:00'},{'count':53,'datetime':'2020-07-15T00:00:00'}]";
return View();
}
2. Views
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var result = #Html.Raw(ViewData["data"]);
this.console.log(result);
var DataItem = [];
for (var i = 0; i < result.length; i++) {
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "Date Time Formatting"
},
data: [{
type: "column",
dataPoints: DataItem
}]
});
chart.render();
}
</script>

How to show Azure Cosmos DB data using C# .net MVC framework on google marker map?

I am trying to achieve google marker map for data from Cosmos Db using C# .net MVC framework. I am not able to pass data to google maps javascript. I have added my code for reference. Please help. Thanks
I am new c# developer. I am using Azure Cosmos db database for application.I tried different method to pass data to Google maps script but it not working.
Model:
public class Device
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "Name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "Address")]
public string Address { get; set; }
[JsonProperty(PropertyName = "Lat")]
public double Lat { get; set; }
[JsonProperty(PropertyName = "Long")]
public double Long { get; set; }
}
Controller:
public class DeviceController : Controller
{
public async Task<ActionResult> MapAsync()
{
var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
return View();
}
View:
#model IEnumerable<WebApplication1.Models.Device>
<script>
#foreach (var item in Model)
{
Html.Raw(" var features = [{position: new google.maps.LatLng(" + item.Lat + "," + item.Long + "), type: 'parking' },];");
}
</script>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(-33.91722, 151.23064),
mapTypeId: 'roadmap'
});
var iconBase = 'http://localhost:20557/Content/Images/';
var icons = {
parking: {
icon: iconBase + 'trafficlight-green.png'
}
};
// Create markers.
features.forEach(function (feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
});
}
</script>
above is the last thing I tried still no help. Please let me know if you want any more information to help me. New to posting questions here.
Please refer working sample created on Net Core MVC in here
Take a look at index action in Home controller and index.cshtml view.
In your code at first you need to pass Modal to view.
Your Code:
var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
return View();
Should pass modal to view like below.
var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
return View(items);
.Creation of features array in view is incorrect
#foreach (var item in Model)
{
Html.Raw(" var features = [{position: new google.maps.LatLng(" + item.Lat + "," + item.Long + "), type: 'parking' },];");
}
Just create Javascript array from c# list in View like
var locationArray = #Html.Raw(Json.Serialize(ViewBag.Locations));
So Update script section in view can be like this. Please refer github link for actual working sample
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
$(document).ready(function() {
initMap();
var locationArray = #Html.Raw(Json.Serialize(ViewBag.Locations));
var newArray = locationArray.map((value) => {
return {
position: new google.maps.LatLng(value.lat, value.lon),
type:'parking'
}
});
// Create markers.
newArray.forEach(function (feature) {
var marker = new google.maps.Marker({
position: feature.position,
map: map
});
});
});
Note: In my sample soultion I have passed list of locations to view using view bag. you can use passing as Modal.
Out put will be like this
Edit: To populate javascript array from list can follow this way also.
var locationArray = [];
#foreach (var item in ViewBag.Locations)
{
#:locationArray.push("{lat:#item.lat, lon:#item.lon}");
}
Thanks all for your help #Erik and #Jeevan your suggestion helped a lot.for anyone else trying to achieve same thing here is viewcode:
function initialize() {
// Enable the visual refresh
google.maps.visualRefresh = true;
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 10
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// ADD FULL SCREEN BUTTON
// map.controls[google.maps.ControlPosition.TOP_RIGHT].push(
// FullScreenControl(map)
// );
google.maps.event.addListener(map, "idle", function () {
$("#map-loader-container").css("background", "none");
});
// get all signs and create a json object from the array
// var signs = '.json_encode($this->_data['items']).';
// creates the var to hold all corrdenates so we can center the map around them later
var myLatLngBounds = new google.maps.LatLngBounds();
// create the container for the Info Window
var infoWindow = new google.maps.InfoWindow({
content: "",
maxWidth: 500,
minWidth: 400
});
// create the marker
#foreach (var item in Model)
{<text>
var myLatLng = new google.maps.LatLng(#Html.DisplayFor(modelItem => item.Lat), #Html.DisplayFor(modelItem => item.Long)); // set the coordenates
myLatLngBounds.extend(myLatLng); // add the marker to be centered in the map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(#Html.DisplayFor(modelItem => item.Lat), #Html.DisplayFor(modelItem => item.Long)),
map: map,
icon: "/Content/Images/green.png",
//optimized: false,
title: "#Html.DisplayFor(modelItem => item.Name)",
html:<h4> #Html.DisplayFor(modelItem => item.Name) </h4>
<div id="bodyContent">
<p> #Html.DisplayFor(modelItem => item.Address)<br /></p>
</div>
});
google.maps.event.addListener(marker, "click", function () {
infoWindow.setContent(this.html);
infoWindow.open(map, this);
});
</text>
}
// centers the map around the coordinates
map.setCenter(myLatLngBounds.getCenter());
map.fitBounds(myLatLngBounds);
//console.info(map.getZoom());
//map.setZoom(1);
var listener = google.maps.event.addListener(map, "idle", function () {
if (map.getZoom() > 15) map.setZoom(15);
google.maps.event.removeListener(listener);
});
}
// Asynchronously Loading the API
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?key=xxxxxx0&callback=initialize";
document.body.appendChild(script);
}
// Load the API after page finish rendering
window.onload = loadScript;

Data column(s) for axis #0 cannot be of type string - Google Charts

I'm trying to display some data in Google Charts but get this error:
Data column(s) for axis #0 cannot be of type string..
I have two properties from this class:
public class GAStatistics
{
public string Date { get; set; }
public string Visitors { get; set; }
}
I'm passing this a list of these properties from this controller:
public class GAStatisticsController : Controller
{
//GET: /ShopStatistics/
public ActionResult GetData()
{
return Json(CreateCompaniesList(), JsonRequestBehavior.AllowGet);
}
private IEnumerable<GAStatistics> CreateCompaniesList()
{
List<GAStatistics> ListGaVisitors = new List<GAStatistics>();
foreach (var row in d.Rows)
{
GAStatistics GaVisits = new GAStatistics(row[0], row[1]);
ListGaVisitors.Add(GaVisits);
}
return ListGaVisitors;
}
}
To this view of which I pass the list from the controller:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.load("visualization", "1", { packages: ["treemap"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get('/GAStatistics/GetData', {},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Date');
tdata.addColumn('string', 'Visitors');
for (var i = 0; i < data.length; i++) {
//tdata.addRow([data[i].Year, data[i].Salary, data[i].Expense]);
tdata.addRow([data[i].Date, data[i].Visitors]);
}
var options = {
title: "Expenses, salary For the current year"
};
var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
chart1.draw(tdata, options);
});
}
</script>
Any idea?
I have tested your example and found out that the main issue is because the second column Visitors should be a number instead of a string.
I have replaced the column type in the tdata.addColumn('number', 'Visitors'); line and added parseInt inside the loop:
tdata.addColumn('date', 'Date');
tdata.addColumn('number', 'Visitors');
// sample data: var data = [{ Date: "20140124", Visitors: "873" }, { Date: "20140125", Visitors: "875" }];
for (var i = 0; i < data.length; i++) {
var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4,2) + "-" + data[i].Date.substr(6,2);
tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
}
Also the first column Date could have remained a string, but I replaced its type to be date and added new Date conversion as well.

how to import JSON data into VS2012 to plot highcharts

I want to import the data from JSON file into my VS2012 c# code so that I can plot my highcharts based on the data in JSON file.
I have checked many video on youtube and file docs but couldnt locate single code that runs and give an output as required.
Do give me a sample code that will map a data from JSON file, use it in vs2012 and plot the highcharts.
----------------Updated Question-------------
Below is the function I am trying to call in java-script where I want to evoke data from JSON format, but I am not able to call my function, below is my code
<script>
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
alert("outside");
$.getJSON('data.json', function (data) {
alert("INside");
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
and want to pass the data to the highcharts ,Since I am novice, any help will be greatly appreciated.
==============EDIT 2 =====================================
the Json file am trying to use for the data is in following format.
[
[1,12],
[2,5],
[3,18],
[4,13],
[5,7],
[6,4],
[7,9],
[8,10],
[9,15],
[10,22]
]
Thank You.
If JSON file is not rendering on the browser and your are getting 404 error then you might be facing the mime type handling problem, please refer the below link which resolves the issue,
getJSON method does not work
ASP.NET MVC Server Code:
namespace ABPMVCTest.Web.Controllers
{
[AbpMvcAuthorize]
public class HomeController : ABPMVCTestControllerBase
{
static Random _ran=new Random();
public ActionResult Index()
{
return View();
}
public ContentResult GetJsonResult()
{
var dataList = new List<ChartDataFormat>();
GetData(dataList, "总收入");
GetData(dataList, "投币收入");
GetData(dataList, "扫码充电收入");
GetData(dataList, "售线收入");
var dataJsonStr=JsonConvert.SerializeObject(dataList,new JsonSerializerSettings(){ContractResolver = new CamelCasePropertyNamesContractResolver()});
return Content(dataJsonStr);
}
private static List<ChartDataFormat> GetData(List<ChartDataFormat> dataList, string key)
{
var list = new List<int>();
for (int i = 0; i < 7; i++)
{
list.Add(_ran.Next(1, 3000));
}
dataList.Add(new ChartDataFormat
{
Name = key,
Data = list
});
return dataList;
}
}
class ChartDataFormat
{
public string Name { get; set; }
public List<int> Data { get; set; }
}
}
Client javascript Code:
$(function() {
Highcharts.setOptions({
lang: {
printChart: '打印图表',
downloadJPEG: '下载为JPEG图片',
downloadPDF: '下载为PDF',
downloadPNG: '下载为PNG图片',
downloadSVG: '下载为SVG矢量图',
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
weekdays: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
shortMonths: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
}
});
var nowDate = new Date();
var option = {
chart: {
type: 'area'
},
title: {
text: '收入趋势图'
},
subtitle: {
text: '没有选择时间范围的话,默认显示当日/月前后3天/月的数据'
},
credits: {
enabled:false
},
xAxis: {
type: 'datetime',
tickmarkPlacement: 'on',
title: {
enabled: false
},
dateTimeLabelFormats: {
day: "%Y-%m-%d",
week: "%A",
month: "%Y-%m",
year: "%Y"
}
},
yAxis: {
title: {
text: '单位:元'
},
labels: {
formatter: function() {
return this.value;
}
}
},
tooltip: {
shared: true,
valueSuffix: ' 元',
dateTimeLabelFormats: {
day: "%Y-%m-%d,%A",
week: "%A开始, %Y-%m-%d",
month: "%Y-%m",
year: "%Y"
}
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
},
series: {
pointStart:Date.UTC(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate()-3) ,
pointInterval: 24 * 36e5 //一天
}
},
series: [{}]
}
var url = "/Home/GetJsonResult";
$.getJSON(url, function(data) {
option.series = data;
$('#container').highcharts(option);
});
});

Categories

Resources