I am trying to display a google chart with dynamic data when my page loads. For clarification I'm using webMatrix (asp.net, c#, sql db).
I have c# codebehind which is querying my main database every 5 minutes and storing the data in a server database "Target".
My goal is to use "Target" as the datasource for the google chart. I'm really confused by the google chart documentation because all of the examples are showing javascript code with hardcoded data. How can I manipulate the javascript so that it contains my dynamic data?
<script>
function initialize() {
var db = 'Target'
var query = new google.visualization.Query(db);
query.setQuery('select Problem group by Queue');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.PieChart(document.getElementById('chart'));
chart.draw(data, {width: 400, height: 240, is3D: true});
}
</script>
I was able to figure this one out...
I didn't realize that razor syntax allows codebehind variables within a script.
C#
{
int a = 100;
int b = 350;
}
Javascript
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
dataArray = [];
dataArray[0] = ['0', 'Title1', 'Title2'];
dataArray[1] = ['Element 1', #a, 0];
dataArray[2] = ['Element 2', 0, #b];
function drawChart() {
//var dt = new google.visualization.DataTable();
//dt.addRows(data);
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'Tickets',
vAxis: { titleTextStyle: { color: 'red'} },
backgroundColor: 'lightgray'
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Related
I am trying to build an autocomplete, but I have troubles patching along the parts.
First, my view include this field:
<p>#Html.TextBoxFor(_item => _item.mCardName, Model.mCardName, new { #class = "cardText", id = "card_name"} ) </p>
Very simple. Next, the javascript call:
<script type="text/javascript">
$(function() {
$('#card_name').autocomplete({
minlength: 5,
source: "#Url.Action("ListNames", "Card")",
select: function (event, ui) {
$('#card_name').text(ui.item.value);
},
});
});
</script>
Which calls this method:
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
If i insert the "Power" word, the JSON data is posted back like this:
{"ContentEncoding":null,"ContentType":null,"Data":[{"CARD_NAME":"Power Armor"},{"CARD_NAME":"Power Armor (Foil)"},{"CARD_NAME":"Power Artifact"},{"CARD_NAME":"Power Conduit"},{"CARD_NAME":"Power Conduit (Foil)"},{"CARD_NAME":"Power Leak"},{"CARD_NAME":"Power Matrix"},{"CARD_NAME":"Power Matrix (Foil)"},{"CARD_NAME":"Power of Fire"},{"CARD_NAME":"Power of Fire (Foil)"},{"CARD_NAME":"Power Sink"},{"CARD_NAME":"Power Sink (Foil)"},{"CARD_NAME":"Power Surge"},{"CARD_NAME":"Power Taint"},{"CARD_NAME":"Powerleech"},{"CARD_NAME":"Powerstone Minefield"},{"CARD_NAME":"Powerstone Minefield (Foil)"}],"JsonRequestBehavior":0,"MaxJsonLength":null,"RecursionLimit":null}
For reference purpose, here are two of the scripts that run:
<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
However nothing is displayed. I would have liked to see the results displayed like a normal autocomplete would do. Can anyone help me out making things work?
EDIT
I have been working on this for a while. I have posted up there the new javascript, controller method and results obtained. But the thing still does not work and I would appreciate any help.
for autocompletes, i use the javascriptserializer class. the code goes something like this.
My.Response.ContentType = "application/json"
Dim serializer As JavaScriptSerializer = New JavaScriptSerializer
Dim dt As DataTable = GetDataTable("proc_name", My.Request.QueryString("term"))
Dim orgArray As ArrayList = New ArrayList
For Each row As DataRow In dt.Rows
Dim thisorg As New thisOrg
thisorg.id = row("organization_child_id")
thisorg.value = row("organization_name")
orgArray.Add(thisorg)
Next
My.Response.Write(serializer.Serialize(orgArray))
Public Class thisOrg
Public id As Integer
Public value As String
End Class
basically just takes a datatable, adds a series of objects to the array, then serializes it.
Finally! After taking a break, I got my answer.
See this?
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
As it happens, I was building a Json object OF another Json object. So that's why the data was not passed properly.
I've rebuilt the method, made it work, and refined it like this:
public JsonResult ListCardNames(string term)
{
using (BlueBerry_MagicEntities db = new BlueBerry_MagicEntities())
{
db.Database.Connection.Open();
var results = from cards in db.V_ITEM_LISTING
where cards.CARD_NAME.ToLower().StartsWith(term.ToLower())
select cards.CARD_NAME + " - " + cards.CARD_SET_NAME;
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return result;
}
And my javascript action:
<script type="text/javascript">
$(function() {
$('#searchBox').autocomplete({
source: function(request, response) {
$.ajax({
url: "#Url.Action("ListCardNames")",
type: "GET",
dataType: "json",
data: { term: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item, value1: item };
}));
}
});
},
select:
function(event, ui) {
$('#searchBox').val(ui.item);
$('#cardNameValue').val(ui.item);
return false;
},
minLength: 4
});
});
</script>
And now everything works like a charm.
How do I plot highchart Gauge with JSON Data?
I am working on highchart gauge, I got succes in showing the latest data from the database. I used JavaScriptSerializer for that
The code is..
<script type="text/javascript">
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'gauge',
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
//Other char parameter comes here
}
function (chart) {
setInterval(function () {
$.getJSON("S14.aspx", function (data, textStatus) {
console.log(data);
$.each(data, function (index, wind) {
var point = chart.series[0].points[0],
newVal = wind;
point.update(newVal);
});
});
}, 3000);
});
The code for JSON is
public string chartData1
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
List<double> _data = new List<double>();
GetData();
foreach (DataRow row in dt.Rows)
{
_data.Add((double)Convert.ToDouble(row["S11"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData1 = jss.Serialize(_data);
}
My JSON looks like
[1387204961992.4268,72]
Well the problem is that the dial of gauge is not moving according to the last values i need to refresh the page for that. I know this is happening because the GetData function is being executed only one time. I am stuck here.
How do I get the dial move according to the last values updates in the database?
Try to place this part of code
setInterval(function() {
$(function() {
$.getJSON('S12.aspx', function(data) {
$.each(data, function(val) {
if (val !== null)
{
var point = chart.series[0].points[0];
point.update(val);
}
});
});
})
},2000)
Inside callback chart, like here: http://www.highcharts.com/demo/gauge-speedometer
If you receive any errors,please attach.
I think there is a bug or something in the visual studio 2012 . I just paste the entire code on the new aspx page it it got working. I have not done anything else I just pasted the code on another page.
<script type="text/javascript">
$(function () {
$('#container1').highcharts({
chart: {
type: 'gauge',
alignTicks: false,
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
title: {
text: 'Pressure Meter'
},
pane: {
startAngle: -150,
endAngle: 150
},
yAxis: [{
min: 0,
max: 1000,
lineColor: '#339',
tickColor: '#339',
minorTickColor: '#339',
offset: -25,
lineWidth: 2,
labels: {
distance: -20,
rotation: 'auto'
},
tickLength: 5,
minorTickLength: 5,
endOnTick: false
}, {
min: 0,
max: 1000,
tickPosition: 'outside',
lineColor: '#933',
lineWidth: 2,
minorTickPosition: 'outside',
tickColor: '#933',
minorTickColor: '#933',
tickLength: 5,
minorTickLength: 5,
labels: {
distance: 12,
rotation: 'auto'
},
offset: -20,
endOnTick: false
}],
series: [{
name: 'Pressure',
data: [80],
dataLabels: {
formatter: function () {
var psi = this.y,
bar = Math.round(psi / 14.50);
return '<span style="color:#339">' + psi + ' psi</span><br/>' +
'<span style="color:#933">' + bar + ' bar</span>';
},
backgroundColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#DDD'],
[1, '#FFF']
]
}
},
tooltip: {
valueSuffix: ' psi'
}
}]
},
// Add some life
function (chart) {
setInterval(function () {
$.getJSON("S12.aspx", function (data, textStatus) {
$.each(data, function (index, wind) {
var point = chart.series[0].points[0],
newVal = wind;
point.update(newVal);
});
});
}, 3000);
});
});
</script>
In order for the chart to update, the browser somehow needs to request the latest data from the server. There are two ways it can do this:
A page refresh - the whole page is fetched again, with the latest data.
An Ajax request. This makes a request for just the data, without re-loading the entire page.
I presume you would like to update the chart without reloading the entire page. In order do to this, you need to find out about making ajax requests using jquery.
The highcharts site has some resources which will help you (e.g. http://www.highcharts.com/docs/working-with-data/preprocessing-live-data). You need to learn how to make an ajax call in javascript, and use the returned data to update your chart. You will also need to write the server side part which returns the ajax data. The example given is in php, but it should be fairly straight forward to do something similar in asp.net.
I have a problem in How to use javascript variables in C# and vise versa : I have this Model passing to the view:
public List<Tache> Get_List_Tache()
{
Equipe _equipe = new Equipe();
List<Tache> liste_initiale = _equipe.Get_List_tache();
return liste_initiale;
}
It's a list of objects Tache in which I'd like to use it's three fields Tache_description, Begin_date and End_date.
In my JavaScript code I have this function and it works fine:
<script>
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
editable: true,
events: [
#foreach (var m in Model.Get_List_Tache())
{
#:{title : #m.Tache_description , start: #m.Begin_date , end : #m.Begin_date }
}
]
});
});
</script>
The values of the array events are just for test, and I need to fill events by the value of the Model. For each element like this: title = Tache_description, start = Begin_date and end = End_date.
So how can I do this task? Any suggestions?
Try this,
foreach (var item in YourList)
{
events: [{ title: '#item.title', start: '#item.start', end: '#item.end'}]
}
So, in this code just replace name your model entity.
Make a foreach razor loop within javascript :
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
header: {left: 'prev,next today',center: 'title',right: 'month,agendaWeek,agendaDay'},
editable: true,
events: [
#
{
bool isFirst = true;
}
#foreach(var m in Model)
{
if(!isFirst)
{
#:,
}
#:{title: #m.Tache_description, ...<other properties here>}
isFirst = false;
}
]
});
For title, you can do title = "#Tache_description"
Not sure about the format/type of your Begin_date and End_date, you may need some function to read the date into a javascript format. Shouldnt be that hard.
Loop through each element and add the elements to the events array. It is something like...
events = new Array()
#foreach(tache in list){
item = { blah : blah, blah : blah };
events.push(item);
}
for each c# item in this c# list, write these lines of javascript. You may end up with a very long javascript code block, but it should do the trick. Above is pseudocode.
To add to Darin's answer: If you need the server-side variables in an external JavaScript file, take a look this blog post: Generating External JavaScript Files Using Partial Razor Views
1: if your model is expecting the list of Tache then you have the whole list you can manipulate.
2: you can get the data using jquery ajax as json data by calling your action Get_List_Tache().
Assuming this javascript is inline in your page you could do the following:
#model IList<Tache>
<script type="text/javascript">
var events = #Html.Raw(Json.Encode(Model.Select(x => new { title = x.Description, start = x.Begin.ToString("o"), end = x.End.ToString("o") })));
$('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: events
});
</script>
This example assumes that your Tache model has properties Description, Begin and End:
public class Tache
{
public string Description { get; set; }
public DateTime Begin { get; set; }
public DateTime End { get; set; }
}
And if this script is in a separate javascript file you could still set a global events variable in your view which will later be used by your script. Alternatively you could fetch this model using an AJAX call.
I was trying to customize google Column chart to add my own data from controller.
I found easy solution but if someone knows better approach I am happy to modify my code.
Assuming that we copy the code from https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="width:50%;float:left"></div>
So the first think I wanted to amend was to display Category name and number of orders.
Solution was simple, I just removed Expensed so it looked like this:
['Category', 'Orders'],
['2004', 1000,],
['2005', 1170, ],
['2006', 660, ],
['2007', 1030, ]
But those are hard coded data and I wanted to have my own category names and name of orders from my Data base.
I created in controller custom string and then pass it to script.
Controller:
foreach (var d in model.DinerCategoryOrders) // Build string for google chart js
{
// ['Pre-School', 1000], Template
GoogleOrdersCount += "['" + d.CategoryName + "', " + d.OrdersCount + "],";
}
model.OrdersForGoogleChart = "google.visualization.arrayToDataTable([['Category', 'Orders']," + GoogleOrdersCount +" ]);";
return model;
In View
I replaced data variable definition simply with my string that I built in controller:
#Html.Raw(Model.OrdersForGoogleChart)
so final build looks like that:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = #Html.Raw(Model.OrdersForGoogleChart)
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I found amazing that Razor in Asp.Net MVC speaks with js and js will digest string that was passed through razor without any issues.
If you find a beter solution to I believe common problem let us know!
I am using ASP.NET MVC in C#
I have a page where the user can move different Widgets around the page, and I now need a method to save the state of the widgets. I am using jQuery in the HTML page, and the jQuery posts the new page layout using JSON. I am unsure how to read the JSON in the controller.
The code I'm using is based on this example here - http://webdeveloperplus.com/jquery/saving-state-for-collapsible-drag-drop-panels/, but the code for saving the result is in PHP.
jQUERY
<script type="text/javascript" >
$(function () {
$('.dragbox')
.each(function () {
$(this).hover(function () {
$(this).find('h2').addClass('collapse');
}, function () {
$(this).find('h2').removeClass('collapse');
})
.find('h2').hover(function () {
$(this).find('.configure').css('visibility', 'visible');
}, function () {
$(this).find('.configure').css('visibility', 'hidden');
})
.click(function () {
$(this).siblings('.dragbox-content').toggle();
//Save state on change of collapse state of panel
updateWidgetData();
})
.end()
.find('.configure').css('visibility', 'hidden');
});
$('.column').sortable({
connectWith: '.column',
handle: 'h2',
cursor: 'move',
placeholder: 'placeholder',
forcePlaceholderSize: true,
opacity: 0.4,
start: function (event, ui) {
//Firefox, Safari/Chrome fire click event after drag is complete, fix for that
if ($.browser.mozilla || $.browser.safari)
$(ui.item).find('.dragbox-content').toggle();
},
stop: function (event, ui) {
ui.item.css({ 'top': '0', 'left': '0' }); //Opera fix
if (!$.browser.mozilla && !$.browser.safari)
updateWidgetData();
}
})
.disableSelection();
});
function updateWidgetData() {
var items = [];
$('.column').each(function () {
var columnId = $(this).attr('id');
$('.dragbox', this).each(function (i) {
var collapsed = 0;
if ($(this).find('.dragbox-content').css('display') == "none")
collapsed = 1;
//Create Item object for current panel
var item = {
id: $(this).attr('id'),
collapsed: collapsed,
order: i,
column: columnId
};
//Push item object into items array
items.push(item);
});
});
//Assign items array to sortorder JSON variable
var sortorder = { items: items };
//Pass sortorder variable to server using ajax to save state
$.post('/Widgets/SaveLayout', 'data=' + $.toJSON(sortorder), function (response) {
if (response == "success")
$("#console").html('<div class="success">Saved</div>').hide().fadeIn(1000);
setTimeout(function () {
$('#console').fadeOut(1000);
}, 2000);
});
alert(sortorder);
}
I am willing to consider alternative ways to do this, as I may not have chosen the best way to do this.
Phil Haack's blog post http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx specifically handles the problem you are trying to solve and it works great.
Hope this helps.
Why not use a cookie? This would save you from having to pull that data back and forth from the server so much.