ASP.NET CORE MVC With Google Charts - No Data - asp.net-core

Trying to implement Google Chart with ASP.Net CORE MVC.
Been at it for two days, but I can not figure out my mistake. I don't get an error, and I can see the array in the console, but no data.
VIEWMODEL
public class ZipCodes
{
public string ZipCode { get; set; }
public int ZipCount { get; set; }
}
CONTROLLER
public ActionResult IncidentsByZipCode()
{
var incidentsByZipCode = (from o in _context.Incident
group o by o.ZipCode into g
orderby g.Count() descending
select new
{
ZipCode = g.Key,
ZipCount = g.Count()
}).ToList();
return Json(incidentsByZipCode);
}
VIEW
function IncidentsByZipCode() {
$.ajax({
type: 'GET',
url: '#Url.Action("IncidentsByZipCode", "Controller")',
success: function (response) {
console.log(response);
var data = new google.visualization.DataTable();
data.addColumn('string', 'ZipCode');
data.addColumn('number', 'ZipCount');
for (var i = 0; i < response.result.length; i++) {
data.addRow([response.result[i].ZipCode, response.result[i].ZipCount]);
}
var chart = new google.visualization.ColumnChart(document.getElementById('incidentsByZipCode'));
chart.draw(data,
{
title: "",
position: "top",
fontsize: "14px",
chartArea: { width: '100%' },
});
},
error: function () {
alert("Error loading data!");
}
});
}

Because the api you use is not Column Chart, the data cannot be added and rendered correctly. According to the official example, you need to make some changes.
Here is the ajax code.
<script>
//Generate random colors
function bg() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ',' + g + ',' + b + ")";
}
function IncidentsByZipCode() {
$.ajax({
type: 'GET',
url: '#Url.Action("IncidentsByZipCode","home")',
success: function (response) {
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
var obj = [
["Element", "Density", { role: "style" }],
];
$.each(response, function (index, value) {
obj.push([value.zipCode, value.zipCount, bg()])
})
var data = google.visualization.arrayToDataTable(obj);//This is method of Column Chart
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var chart = new google.visualization.ColumnChart(document.getElementById('incidentsByZipCode'));
chart.draw(data,
{
title: "",
position: "top",
fontsize: "14px",
chartArea: { width: '100%' },
});
}
},
error: function () {
alert("Error loading data!");
}
});
}
IncidentsByZipCode()
This is the controller.
public ActionResult IncidentsByZipCode()
{
//var incidentsByZipCode = (from o in _context.Incident
// group o by o.ZipCode into g
// orderby g.Count() descending
// select new
// {
// ZipCode = g.Key,
// ZipCount = g.Count()
// }).ToList();
var incidentsByZipCode = new List<ZipCodes>
{
new ZipCodes{ ZipCode="code1", ZipCount=3},
new ZipCodes{ZipCode="code2",ZipCount=4},
new ZipCodes{ZipCode="code3",ZipCount=2},
new ZipCodes{ZipCode="code4",ZipCount=9},
};
return Json(incidentsByZipCode);
}
Result, and you can also refer to this document
.

Related

Send back FullCalendar events to .NET with AJAX

I would like to sendback FullCalendar events to .NET with an AJAX request. I create a custom button for that :
#{
ViewData["Title"] = "Planning visites";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>#ViewData["Title"]</h1>
<div id='calendar'></div>
#section scripts
{
<script>
let date = new Date();
let month = String(date.getMonth() + 1).padStart(2, '0');
let day = String(date.getDate()).padStart(2, '0');
let year = date.getFullYear();
let dateDuJour = year + '-' + month + '-' + day;
let dateDuJourplusunan = (year + 1) + '-' + month + '-' + day;
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
//themeSystem: 'bootstrap5',
//plugins: [ timeGridPlugin ],
initialView: 'timeGridWeek',
selectable: true,
selectOverlap: false,
//selectMirror: true,
validRange: {
start: dateDuJour,
end: dateDuJourplusunan
},
customButtons: {
enregistrermodifs: {
text: 'enregistrer',
click: function() {
var eventsobj = calendar.getEvents();
var data = JSON.stringify(eventsobj);
//var data = JSON.serialize(eventsobj);
alert(data);
$.ajax({
type: 'POST',
url: '#Url.Action("MAJAgenda","Agenda")',
//contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // when we use .serialize() this generates the data in query string format. this needs the default contentType (default content type is: contentType: 'application/x-www-form-urlencoded; charset=UTF-8') so it is optional, you can remove it
contentType: 'application/json; charset=utf-8',
data: data,
success: function(result) {
alert('Successfully received Data ');
console.log(result);
},
error: function() {
alert('Erreur : enregistrement non effectué');
console.log('Failed');
}
});
}
}
},
headerToolbar: {
left: 'prev,next,today,enregistrermodifs',
center: 'title',
right: 'dayGridMonth,timeGridWeek,dayGridDay'
},
buttonText: {
today: 'Aujourdhui',
month: 'mois',
week: 'semaine',
timeGridWeek: 'jour',
day: 'jour',
list: 'liste'
},
initialDate: dateDuJour,
navLinks: true, // can click day/week names to navigate views
editable: true,
dayMaxEvents: true, // allow "more" link when too many events
events:'#Url.Action("RecupDonneesAgenda","Agenda")?annonceId=#ViewBag.AnnonceId',
select: function(info) {
calendar.addEvent({
//id: info.startStr,
title: 'Indisponibilité',
start: info.startStr,
end: info.endStr,
allDay: false
});
},
eventClick: function(info) {
var eventobj = info.event;
eventobj.remove();
}
});
calendar.render();
calendar.setOption('locale', 'fr');
});
</script>
}
Here's my model in .NET :
public class AgendaAJAX
{
public string? title { get; set; }
public DateTime? start { get; set; }
public DateTime? end { get; set; }
}
And here's my action method :
[HttpPost]
public async Task<IActionResult> MAJAgenda(AgendaAJAX? agenda)
{
string userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
////List<Agenda> agenda = await _context.Agendas.Where(a => a.AnnonceID == annonceId && a.Personne1 == userID).ToListAsync();
//JsonResult result = new JsonResult(agenda);
return View("Agenda");
}
THE AJAX call works well : here's the JSON data :
[{"title":"Indisponibilité","start":"2022-06-09T07:30:00+02:00","end":"2022-06-09T12:30:00+02:00"},{"title":"Indisponibilité","start":"2022-06-10T10:00:00+02:00","end":"2022-06-10T15:00:00+02:00"},{"title":"Indisponibilité","start":"2022-06-11T07:00:00+02:00","end":"2022-06-11T09:30:00+02:00"}]
The problem is that I don't receive any data in the action method : agenda remains null.
I don't understand why.
If you can help me please.
Thanks.

Fine Uploader - objectProperties - Key

I have 1 page whick give to user add new car to his cars collection.
User MUST to add minimum 1 image to this car item.
In AWS S3 service I save images in this path architecture:
bucket_name/cars/HERE_IS_USER_ID/HERE_IS_CAR_ID/and here photos
I use fine uploader.
ANd If i do add car in 2 step - all is going good
In 1 step I add to my database car - and send from server side userId and new car Id.
And then in step 2 I init Fine uploader with this id:
Below Code:
(function () {
'use strict';
angular
.module('cars.services.fineUploader', ['ngResource'])
.factory('FineUploader', ['$resource', '$http', 'AppConfig', function ($resource, $http, AppConfig) {
return function (divId, templateName, autoUpload, foldersBtn, uploadSuccessCallback, type, parentId, id) {
var key = '';
var keyExist = false;
getKey();
if (!qq.supportedFeatures.folderSelection) {
document.getElementById(foldersBtn).style.display = "none";
}
var uploader = new qq.s3.FineUploader({
element: document.getElementById(divId),
template: templateName,
autoUpload: autoUpload,
request: {
endpoint: 'carsbucket.s3.amazonaws.com',
accessKey: 'ACCESS',
},
extraButtons: [
{
element: document.getElementById(foldersBtn),
folders: true
}
],
signature: {
endpoint: AppConfig.apiUrl + 'api/AmazonS3/GetSignature'
},
uploadSuccess: {
endpoint: uploadSuccessCallback()
},
iframeSupport: {
localBlankPagePath: '/success.html'
},
objectProperties: {
key: function (id) {
var fileName = uploader.getName(id);
var ext = qq.getExtension(fileName);
return key+ '/' + fileName + "." + ext;
}
}
});
return {
Uploader: function () {
return uploader;
},
StartUpload: function () {
uploader.uploadStoredFiles();
},
InitUploader: function () {
while (!keyExist) {
getKey();
}
}
};
function getKey() {
var itemRequest = {
"ItemType": type,
"ParentId": parentId,
"ItemId": id
};
$http.post("http://localhost:42309/api/AmazonS3/GetItemKey", itemRequest).success(function (data, status) {
key = data;
keyExist = true;
});
}
}
}]);
})();
And this is code how I init this service:
function Uploader(shopId, shopItemId) {
vm.step = 2;
uploader = FineUploader('s3FU', 'qq-template-gallery', false, 'foldersButton', testCallback, 1, shopId, shopItemId);
}
Now I want to do all ADD ITEM logic in 1 step
But I dont know how do it - because I need init FineUploader - but I dont have carId and UserId
.........

How to join two collections in a json store?

I am working on IBM Worklight. I need to access data from two collections. Is there any solution for joining the 2 collections and get the required fields ?
JSONSTORE does not have the ability to combine collections.
However the follow blog post details one way to achieve this: https://mobilefirstplatform.ibmcloud.com/blog/2015/02/24/working-jsonstore-collections-join/
Create a collection:
var OrdersCollection = {
orders: {
searchFields: {
order_id: 'integer',
order_date: 'string'
},
additionalSearchFields: {
customer_id: 'integer'
}
}
};
var CustomerCollection = {
customers: {
searchFields: {
customer_name : 'string',
contact_name : 'string',
country : 'string'
},
additionalSearchFields : {
customer_id : 'integer'
}
}
};
Add data using additional search fields:
var data = [
{order_id : 462, order_date : '1-1-2000'},
{order_id: 608, order_date : '2-2-2001'},
{order_id: 898, order_date : '3-3-2002'}
];
var counter = 0;
var q = async.queue(function (task, callback) {
setTimeout(function () {
WL.JSONStore.get('orders').add(task.data, {additionalSearchFields: {customer_id: task.customer_id}});
callback(++counter);
},0);
},1);
for(var i = 0; i < data.length; i++){
q.push({data : data[i], customer_id: i+1}, function(counter){
console.log("Added Order Doc " + counter);
});
}
q.drain = function(){
setTimeout(function() {
console.log("Finished adding order documents");
WL.JSONStore.get("orders").findAll({filter : ["customer_id", "order_id", "order_date"]})
.then(function (res) {
ordersCollectionData = res;
document.getElementById("orders").innerHTML = JSON.stringify(res, null, "\t");
})
.fail(function (err) {
console.log("There was a problem at " + JSON.stringify(err));
});
},0);
};
Find the documents to merge:
WL.JSONStore.get('orders').findAll({filter : ['customer_id', 'order_id', 'order_date']})
.then(function (res) {
ordersCollectionData = res;
});
Merge
var shared_index = 'customer_id';
var mergedCollection = [];
mergedCollection =_.merge(customerCollectionData, ordersCollectionData, function(a, b){
if(_.isObject(a) && (a[shared_index] == b[shared_index])) {
return _.merge({}, a, b);
}
});

MVC 4 with Google Charts API

I have a chart using Google Charts API, I can display information directly from my view but I want to send the information from the controller, so far I have tried to send the information as Json, The problem is that the chart is being displayed but its all gray and doesnt really shown any information, it just says Other. is there anything I am missing? my controller is
Controller:
public JsonResult GetDataAssets()
{
List<object> data = new List<object>();
data.Add(new[] { "Task", "Hours per Day"});
data.Add(new[] { "Introduction", "100" });
data.Add(new[] { "Basic 1", "75" });
data.Add(new[] { "PHP", "24" });
return Json(data);
}
and in my view I have this
View:
<script type="text/javascript">
function drawVisualization() {
$.post('GetDataAssets', {}, function (d) {
var data = google.visualization.arrayToDataTable(d);
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, { title: "Top Videos", pieHole: 0.4 });
}
)
};
google.setOnLoadCallback(drawVisualization);
</script>
<div id="visualization" style="width: 600px; height: 400px; margin: auto"></div>
Well, I had to rethink the way to do it, instead of sending the JSON I'm sending it to then build the chart information, Here is what I did:
Controller:
public class PieChart
{
public string Name;
public decimal valor;
}
public ActionResult GetData()
{
return Json(CreateDataList(), JsonRequestBehavior.AllowGet);
}
public IEnumerable<PieChart> CreateDataList()
{
List<PieChart> data = new List<PieChart>();
PieChart r = new PieChart() { Name = "Introduction", valor = 20 };
PieChart r1 = new PieChart() { Name = "Basic 1", valor = 24 };
PieChart r2 = new PieChart() { Name = "PHP", valor = 74 };
data.Add(r);
data.Add(r1);
data.Add(r2);
return data;
}
And on the View
<script type="text/javascript">
function drawVisualization() {
$.get('GetData', {}, function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Year');
tdata.addColumn('number', 'Hours');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].valor]);
}
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(tdata, { title: "Top Videos", pieHole: 0.4 });
})
};
google.setOnLoadCallback(drawVisualization);
</script>

Get dropdown value and text in controller mvc4 razor

I am working on MVC4 project. I have form where dropdownlist is populated with text and value field.
#Html.DropDownList("SourceDropDownList", new SelectList(""), "-Select-", new { #class = "validate[required]" })
This dropdown is populated from other dropdown change event
here is that code
function OnSourceFacilityDropDownChange(source, e) {
$("#SourceDropDownList").empty();
var curOpt = new Option('-Select-', "");
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
if (source.value != '') {
var url = getUrl() + '/AdminPanel/GetIns/?id=' + Math.random();
$.ajax({
url: url,
data: { clientid: $("#SourceDropDown").val(), strFacility: source.value }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
$.each(data, function (index, item) {
var curOpt = new Option(item.T, item.T);
curOpt.setAttribute("title", item.T);
$("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
});
},
error: function (request, status, error) { alert("Status: " + status + "\n Exception Handling : \n" + request.responseText); },
complete: function () {
$("#divLoading").hide();
}
});
}
else {
}
}
and code in AdminPanel/GetIns controller is
public JsonResult GetInspection(int clientid, string strFacility)
{
var objlist = (from d in Context.tbl_insp
orderby d.str_insp ascending
where d.clientid.Equals(ClientId))
select new { T= d.str_inspname, V= d.dte_start.Value.ToShortDateString()}).ToArray();
Array InspectionList = objlist;
return Json(InspectionList, JsonRequestBehavior.AllowGet);
}
And in model class i have initialized the property of dropdown
public string SourceDropDownList{ get; set; }
now i am getting only text values of what i select in SourceDropDownList dropdown..
How do i get the value also ??
Try with this,Just Example
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
#Html.DropDownList("CustomerNameId", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")
Script
<script type="text/javascript">
$(document).ready(function () {
$("#CustomerId").change(function () {
var Id = $("#CustomerId").val();
$.ajax({
url: '#Url.Action("GetCustomerNameWithId", "Test")',
type: "Post",
data: { CustomerNameId: Id },
success: function (listItems) {
var STSelectBox = jQuery('#CustomerNameId');
STSelectBox.empty();
if (listItems.length > 0) {
for (var i = 0; i < listItems.length; i++) {
if (i == 0) {
STSelectBox.append('<option value="' + i + '">--Select--</option>');
}
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
else {
for (var i = 0; i < listItems.length; i++) {
STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');
}
}
}
});
});
});
</script>
Controller
public JsonResult GetCustomerNameWithId(string CustomerNameId)
{
int _CustomerNameId = 0;
int.TryParse(CustomerNameId, out _CustomerNameId);
var listItems = GetCustomerNameId(_CustomerNameId).Select(s => new SelectListItem { Value = s.CID.ToString(), Text = s.CustomerName }).ToList<SelectListItem>();
return Json(listItems, JsonRequestBehavior.AllowGet);
}
Model
public class CustomerModel
{
public int CustomerId { get; set; }
public int CustomerNameId { get; set; }
}