MVC 4 with Google Charts API - asp.net-mvc-4

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>

Related

Multiple Pdf Viewer Add Same Page Via Vue Pdf App Component

I want to show two different pdf file (pdf and pdf2) on same page via one component.
When I try to like below, the second pdf file not shown in the page. Do you have any suggestion
<div id="app">
<vue-pdf-app style="height: 50vh;" :pdf="pdf" :config="config"></vue-pdf-app>
<vue-pdf-app style="height: 50vh;" :pdf="pdf2" :config="config"></vue-pdf-app>
</div>
And here is my javascript codes.
new Vue({
components: {
VuePdfApp: window["vue-pdf-app"]
},
data() {
return {
config: {
toolbar: {
toolbarViewerLeft: { findbar: false }
}
},
pdf: getPdf(),
pdf2: getPdf()
};
}
}).$mount("#app");
function getPdf() {
const pdf2 =" base 64 string pdf";
const pdf = "base 64 string pdf1 ";
return base64ToArrayBuffer(pdf);
}
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
Here is my code on codepen
https://codepen.io/canbeywas/pen/yLMpEBg
You can fix this by slightly modifying your code like this:
new Vue({
components: {
VuePdfApp: window["vue-pdf-app"]
},
data() {
return {
config: {
toolbar: {
toolbarViewerLeft: { findbar: false }
}
},
pdf: getPdf(),
pdf2: getPdf2()
};
}
}).$mount("#app");
function getPdf() {
const pdf = "base 64 string pdf1 ";
return base64ToArrayBuffer(pdf);
}
function getPdf2() {
const pdf = "base 64 string pdf2 ";
return base64ToArrayBuffer(pdf);
}
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}

ASP.NET CORE MVC With Google Charts - No Data

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
.

How to Display Show Attachment in Info Window

I am using below code to display identifier popup.if I click on particular point it will display all the information about that point in info window(popup).but even if I specify show attachments true it will not display the attachments.In Map server I have an image for points.so I need to display info window as well as the image.
map.on("load", mapReady);
var parcelsURL = "MY MAP SERVER";
//map.addLayer(new ArcGISDynamicMapServiceLayer(parcelsURL,
// { opacity: 20 }));
function mapReady() {
map.on("click", executeIdentifyTask);
//create identify tasks and setup parameters
identifyTask = new IdentifyTask(parcelsURL);
identifyParams = new IdentifyParameters();
identifyParams.tolerance = 3;
identifyParams.returnGeometry = true;
identifyParams.layerIds = [0];
identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
identifyParams.width = map.width;
identifyParams.height = map.height;
}
function executeIdentifyTask(event) {
identifyParams.geometry = event.mapPoint;
identifyParams.mapExtent = map.extent;
var deferred = identifyTask
.execute(identifyParams)
.addCallback(function (response) {
// response is an array of identify result objects
// Let's return an array of features.
return arrayUtils.map(response, function (result) {
var feature = result.feature;
var layerName = result.layerName;
feature.attributes.layerName = layerName;
if (layerName === 'GridPoint') {
var popupTemplate = new PopupTemplate({
title: "",
fieldInfos: [
{
fieldName: "XX",
visible: true,
label: "XX"
},
{
fieldName: "YY",
visible: true,
label: "YY"
}
],
showAttachments: true
});
//var taxParcelTemplate = new InfoTemplate("",
// "XX: ${XX} <br/> YY: ${YY} <br/> Sample Point Number: ${Sample Point Number} <br/> Point Collected: ${Point Collected} <br/> Major Rabi Crops: ${ Major Rabi Crops} <br/> Major Summer Crop: ${Major Summer Crop} <br/> Soil Type: ${Soil Type} <br/> Major Kharif Crops: ${Major Kharif Crops}");
feature.setInfoTemplate(popupTemplate);
}
//else if (layerName === 'Grid') {
// console.log(feature.attributes.objectid);
// var buildingFootprintTemplate = new InfoTemplate("",
// "OBJECTID: ${OBJECTID}");
// feature.setInfoTemplate(buildingFootprintTemplate);
//}
return feature;
});
});
map.infoWindow.setFeatures([deferred]);
map.infoWindow.show(event.mapPoint);
}
});
someone please help me to display attachments(image) in info window.

Calling HttpGet Method Using Ajax on IpagedListPager Mvc

I want to call HttpGet method on every page using ajax using IpagedList in MVC
Controller [HttpGet]
public ActionResult TestStarted(int TestId,DateTime End_Time,int page=1)
{
ViewBag.ct = 0;
ViewBag.TestId = TestId;
var Questions = GetNoOfQuestions().ToList();
ViewBag.Questions = Questions;
EAssessmentNew.BAL.StudentBal studBal = new EAssessmentNew.BAL.StudentBal();
EAssessmentNew.Dal.Student_Answer_Master _studAnsdal = new EAssessmentNew.Dal.Student_Answer_Master();
String TestName = studBal.FetchTestName(TestId);
ViewBag.TestName = TestName;
ViewBag.EndTime = End_Time;
List<Question> model = new List<Question>();
model = new Test_Planning().Fetch_Question_By_Test(TestId);
ViewBag.total = model.Count();
if (Request.QueryString["cnt"] != null)
{
int count = Convert.ToInt16(Request.QueryString["cnt"].ToString());
List<int> ChkOptions = studBal.GetCheckedAnswers((int)TestId, model[count].QuestionId, (int)(studBal.getStudentId(Session["sname"].ToString())));
ViewBag.ChkOptions = ChkOptions;
int cnt = 0;
if (ChkOptions.Count() != 0)
{
for (int i = 0; i < model[count].Options.Count(); i++)
{
if (model[count].Options[i].OptionId == ChkOptions.ElementAt(cnt))
{
model[count].Options[i].IsChecked = true;
cnt++;
}
else
{
model[count].Options[i].IsChecked = false;
}
if (cnt >= ChkOptions.Count() - 1)
{
cnt = ChkOptions.Count() - 1;
}
}
}
return View(model.OrderByDescending(v => v.Question_Id).ToPagedList(page, 1));
}
else
{
return View(model.OrderByDescending(v => v.Question_Id).ToPagedList(page, 1));
}
}
My View
<script type="text/javascript">
var TestId ='#ViewBag.TestId'
function loadQuestions() {
alert("ok")
$.ajax({
url: '#Url.Action("Student","TestStarted")',
data: { TestId:TestId },
contentType:"application/json",
success:function(responce){
}
});
}
</script>
<div class="pagedList">
#Html.PagedListPager(Model, page => Url.Action( "",new { onclick="loadQuestions()"}), PagedListRenderOptions.TwitterBootstrapPager)
</div>
I have done paging using IpagedList i want to call HttpGet Method Of controller on each and every page but i want this to perform without page refresh i have written ajax for it now i just want to know how can i call that ajax method using #Html.PagedListPager and on onClick event
Just Correct your url in ajax request as :
Instead of this
url: '#Url.Action("Student","TestStarted")'
It should be this
url: '#Url.Action("TestStarted","Student")'
and #Html.PagedListPager produces 'anchor' tag in html so you can put a click event on document as shown :-
$(document).on('click', 'a', function() {
$.ajax({
url: this.href,
type: 'GET',
datatype: "html",
data :{ TestId : $("#TestId").val(), End_Time :$("#End_Time").val(), page :$("#page").val() }
cache: false,
success: function(result) {
$('#results').html('');
$('#results').html(result);
}
});
return false;
});
In above code click event binds with every 'anchor' tag so if you need for specific 'anchor' tags then you can specify class as $(.pager).on('click', 'a', function() {}) and here '#results' is the target div id whose html is coming from controller action in your case this id may be different.

Google maps API geolocation + radar places search

I am trying to use both Geolocation and Places from the google maps API to display a map (at my location) with the nearest places around me. The two examples work seperately but not together.
Can anyone tell me why there is a problem with this? am I overwriting the map with another or doing something else wrong?
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyA93l5zPyIvGB7oYGqzLSk28r5XuIs2Do8
&sensor=true&libraries=places"></script>
<script>
var map;
var service;
var marker;
var pos;
function initialize() {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Located'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
EDIT
Moved the code now so it looks like - Has not fixed the problem of location being undefined.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Located'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});'
Because of async call to navigator.geolocation.getCurrentPosition() which returns immediately, location property of request is undefined. Call to
service.nearbySearch(request,callback);
complains that location is missing. And that is true because pos is not set at that moment.
You have to move this part of code:
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
to
navigator.geolocation.getCurrentPosition(function(position) {
...
map.setCenter(pos);
and make variable infoWindow global.
This is changed initialize() function:
var map;
var service;
var marker;
var pos;
var infowindow;
function initialize() {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
console.log(map);
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Located'
});
map.setCenter(pos);
var request = {
location:pos,
radius:500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,callback);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
console.log('after / to createMarker');
createMarker(results[i]);
}
}
}
}