I got an project in dotnet and i'm trying to use GoogleCharts, but it's not working.
The project is on .net mvc
Here is my code:
Views->Sensor->Chart.cshtml
#{
ViewData["Title"] = "Chart";
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(LoadData);
function LoadData() {
$.ajax({
url: '#Url.Action("ChartJson","Sensor")',
dataType: "json",
type: "GET",
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
success: function(data) {
CreateChart(data);
return false;
}
});
return false;
}
function CreateChart(data) {
var dataArray = [
['Tag', 'Average value']
];
$.each(data, function(i, item) {
dataArray.push([item.tag, item.value]);
});
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'Sensor data per coutry and region',
chartArea: {
width: '50%'
},
colors: ['#b0120a', '#ffab91'],
hAxis: {
title: 'Arithmetic average',
minValue: 0
},
vAxis: {
title: 'Tag'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
return false;
}
</script>
This view is loaded on the url, but there is no graph on it.
I thied to debug the controller class, but the ChartJson() method is never called.
This is the two methods on the controller for the charts draw routine:
Controllers->SensorController.cs
public IActionResult Chart()
{
return View();
}
public JsonResult ChartJson()
{
var sensors = from s in _context.Sensor select s;
var sensorsList = sensors.ToList();
Console.WriteLine("Entrou");
List<ChartData> listChart = new List<ChartData>();
foreach (Sensor s in sensorsList)
{
int value;
bool isNumeric = int.TryParse(s.value, out value);
if (!isNumeric)
continue;
string tag = s.country + "." + s.region;
for (int i = 0; i < listChart.Count; i++)
{
if (listChart[i].tag.Equals(tag))
{
listChart[i].AddValue(value);
break;
}
if (i == listChart.Count - 1)
{
listChart.Add(new ChartData(tag));
break;
}
}
}
return Json(listChart);
}
Can anyone help me? Thanks.
Related
i have a razor project where i implemented DataTables. I'm trying to retrieve data from the database dynamically with ajax in this way:
$('#orariDipendenti').DataTable({
'orderMulti': false,
'stateSave': true,
'paging': true,
'pageLength': 10,
'filter': false,
'processing': true,
'serverSide': true,
'ajax': {
url: '?handler=LoadData',
type: 'POST',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
},
});
my back code is this:
public JsonResult LoadTable()
{
try
{
var idDipendente = HttpContext.Session.GetInt32("IdDipendente");
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
int pagesize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordstotal = 0;
var recordData = context.Pres_Orari.Where(x => x.IdDipendente == idDipendente).ToList();
recordstotal = recordData.Count;
var data = recordData.Skip(skip).Take(pagesize).ToList();
return new JsonResult(new { draw = draw, recordsFiltered = recordstotal, recordsTotal = recordstotal, data = data });
}
catch (Exception)
{
throw;
}
}
the error i get when i open the page is this:
DataTables warning: table id={id} - Invalid JSON response.
I know the broblem is with the returned json but i don't know where. somebody can help me?
Firstly,your handler name is LoadTable,your url in ajax is url: '?handler=LoadData'.You need to change url to url: '?handler=LoadTable'.And here is a working demo(I also change xhr.setRequestHeader("XSRF-TOKEN" to xhr.setRequestHeader("RequestVerificationToken",if your code can work,you don't need to changexhr.setRequestHeader("XSRF-TOKEN"):
cshtml:
#Html.AntiForgeryToken()
<table id="orariDipendenti" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr class="table-info">
<th>IdDipendente</th>
<th>Name</th>
</tr>
</thead>
</table>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script>
<script>
$(function () {
$('#orariDipendenti').DataTable({
'orderMulti': false,
'stateSave': true,
'paging': true,
'pageLength': 10,
'filter': false,
'processing': true,
'serverSide': true,
ajax: {
url: '?handler=LoadTable',
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
},
columns: [
{ data: 'idDipendente' },
{ data: 'name' },
]
});
});
</script>
Model:
public class MyModel1 {
public int IdDipendente { get; set; }
public string Name { get; set; }
}
cshtml.cs(I use fake data to test):
public static List<MyModel1> list = new List<MyModel1> { new MyModel1 { IdDipendente = 1, Name = "name1" }, new MyModel1 { IdDipendente = 2, Name = "name2" }, new MyModel1 { IdDipendente = 3, Name = "name3" } };
public JsonResult OnPostLoadTable()
{
try
{
var idDipendente = 1;
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
int pagesize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordstotal = 0;
var recordData = list.Where(x => x.IdDipendente==idDipendente).ToList();
recordstotal = recordData.Count;
var data = recordData.Skip(skip).Take(pagesize).ToList();
return new JsonResult(new { draw = draw, recordsFiltered = recordstotal, recordsTotal = recordstotal, data = data });
}
catch (Exception)
{
throw;
}
}
}
result:
I want to carry data by onclick function to the next page. All data is carried along with by giving parameter but it doesn't return View from the controller. Please help me. I'm stuck in here two days this is my school project.
OnClick button:
<div class="row">
<div class="col-sm-4"></div>
<button class='btn bg-blue next' onclick="checkamt(#Model.TotalAmt)">Next</button>
</div>
Controller:
public ActionResult ComfirmPay(int e = 0, string TaxType = null, int CurrentAmt = 0)
{
ViewBag.TotalAmt = e;
ViewBag.CurrentAmt = CurrentAmt;
ViewBag.TaxType = TaxType;
return View("ComfirmPay");
}
Ajax:
function checkamt(e) {
var amount = #ViewBag.CurrentAmt;
if (amount < e) {
alert('bad');
window.location.href = 'http://localhost:22822/Home/PayTax';
}
else {
alert('good');
$.ajax({
cache: false,
url: '#Url.Action("ComfirmPay", "Home")',
data: { e: e, taxtype: taxtype, currentamt: currentamt },
beforeSend: function () {
},
success: function () {
},
complete: function () {
}
})
}
}
View:
<div class="col-md-9 col-xs-9">
<p class="text-muted">You have total <b class="text-green">#ViewBag.CurrentAmt</b> points</p>
</div>
Remove the ajax function and do this
window.location.href = "#Url.Action("ComfirmPay", "Home")" + "?e=" + e + "&taxtype=" + taxtype + "¤tamt=" + currentamt
The comment on this post explains a little more about why what you are trying to do does not work.
i think for your purpose there is no need of ajax call. you can use window.location.hrefas follows
function checkamt(e) {
var amount = #ViewBag.CurrentAmt;
if (amount < e) {
window.location.href = 'http://localhost:22822/Home/PayTax';
}
else {
window.location.href = '/Home/ComfirmPay?e='+e+'&taxtype='+taxtype+'¤tamt='+currentamt;
}
}
and in the controller
public ActionResult ComfirmPay(string e, string TaxType, string CurrentAmt)
{
ViewBag.TotalAmt = e;
ViewBag.CurrentAmt = CurrentAmt;
ViewBag.TaxType = TaxType;
return View();
}
I am working with ASP.NET MVC 5, jquery and the datatables plugin in a project. My goal is to use the serverside function of datatables in order to retrieve data of a database and then to display the dat in a datatable. This works fine in one part of my code. Here you can see the jquery code where I use the datatables plugin:
var problemTable = $('#ProblemTable').DataTable({
processing: true, // show message while querying fro data
serverSide: true,
ajax: {
url: "/OverView/LoadProblems"
}
});
As you can see in the following picture, the request is successful and my datatables gets filled as it should in the website.
The request URL looks like this:
So far is everything fine. But now comes the part, which is driving me crazy. In a different jquery script I try to call again the the datatables method for a new datatable. The code looks like this:
$('.DeleteEntity').click(
function () {
try
{
var deleteTable = $('#DeleteTable').DataTable({
processing: true,
serverside: true,
destroy: true,
ajax: {
url: "/Administration/ShowEntriesDelete"
}
});
}
catch (e)
{
console.log(e);
}
});
This Ajax call doesnt work anymore. As you can see the following picture, the action method in C# Code fails.
In this case, the request URL looks like this.
So here is my question: Why do I get this behavior although I use the same function in my jquery code? Or is there something which I got totally wrong?
I think that I have tried everything by now, but I still don´t get it. Both datatables look exact the same in HTML, only id and column headers are different.
I also looked for similar questions, but I couldn't find anything. I would be very glad if someone could give me a hint for this.
Best regards!
EDIT:
#Calvin Ananda
I adapted your answer and added both DataTable functions to one script, just for testing purpose. Here is the hole script.
var troubleshootingIDs = [];
$(document).ready(
function () {
// if I call this method, everything works just fine, the c# code throws an error (which it should) but the ajax method is successfull
var problemTable = $('#ProblemTable').DataTable({
processing: true, // show message while querying fro data
serverSide: true,
"ajax": "/Administration/ShowEntriesDelete"
});
// if I call this method, the ajax method doesnt get called, because there is absolute no data provided in the url
var deleteTable = $('#DeleteTable').DataTable({
processing: true,
serverside: true,
destroy: true,
"ajax": "/Administration/ShowEntriesDelete",
"columns": [
{ "data": "Description" },
{ "data": "Connection" },
{ "data": "Action" }
]
});
var table = $('#reasonTable').DataTable({
pageLength: 2,
lengthChange: false,
columnDefs: [
{
targets: [3],
className: "hide_me"
}
]
}
);
var agentButton = $('.agentButton');
$('td').on('click', '#BadgeContainer', function () {
var IDs = [];
$('#DocList').empty();
$('.DocLinkID').each(function (counter) {
IDs[counter] = $(this).html();
});
console.log(IDs);
$.ajax({
url: "/OverView/GetDocuments",
traditional: true,
data: { IDs: IDs },
content: 'application/json; charset=utf-8',
success: listDocuments
});
});
$('#reasonTable tbody').on('click', 'tr', function () {
$('#SolutionList').empty();
troubleshootingIDs = [];
if ($(this).hasClass('selected')) {
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
var selectedReason = $('.ReasonGuid', this).text();
$.ajax({
url: '/OverView/ReasonJson',
contentType: 'application/json; charset=utf-8',
data: { 'selectedReason': selectedReason },
success: handleJsonForWizard
}
);
}
);
$('.SolutionButton').on('click',
function () {
var indexToRemove = [];
var dummyArray = [];
for (var counter = 0; counter < troubleshootingIDs.length; counter++) {
if ($('#q' + (+counter * 2)).hasClass('btn-active')) {
indexToRemove.push(counter);
}
dummyArray[counter] = troubleshootingIDs[counter];
}
for (var counter = indexToRemove.length - 1; counter >= 0; counter--) {
dummyArray.splice(indexToRemove[counter], 1);
}
$.ajax(
{
url: '/OverView/GetSolutions',
contentType: 'application/json; charset=utf-8',
traditional: true,
data: { troubleshootingIDs: dummyArray },
success: function (json) {
$('#SolutionList').empty();
try {
for (var counter = 0; counter < Object.keys(json).length; counter++) {
$('#SolutionList').append('<li class="list-group-item">' + json[counter] + '</li>');
}
}
catch (err) {
}
}
}
);
}
);
$('#ProblemTable tbody').on('click', '.WizardButton',
function () {
var IdToGet = $(this).attr('id');
var url = '/OverView/Wizard?SelectedID=';
window.location.replace(url + IdToGet);
}
);
// Carousel fuction overriding (doesn't work wiht jquery template)
$('.carousel-control.left').click(
function () {
var parentId = '#' + $(this).parent().attr('id');
$(parentId).carousel('prev');
}
);
$('.carousel-control.right').click(
function () {
var parentId = '#' + $(this).parent().attr('id');
$(parentId).carousel('next');
}
);
// comment to define
$('.row #BackToTable').click(
function () {
window.location.replace("/OverView");
}
);
$('body').on('click', '.AgentButton',
function () {
var idNum = $(this).attr('id');
var num = idNum.substring(1);
$('#' + idNum).toggleClass('btn-active');
if ((num % 2) == 0) {
var numToCompare = +num + 1;
var classToCompare = $('#q' + numToCompare).attr('class');
if (classToCompare == 'btn AgentButton btn-active') {
$('#q' + numToCompare).toggleClass('btn-active');
}
}
else {
var numToCompare = +num - 1;
var classToCompare = $('#q' + numToCompare).attr('class');
if (classToCompare == 'btn AgentButton btn-active') {
$('#q' + numToCompare).toggleClass('btn-active');
}
}
}
);
function handleJsonForWizard(json) {
initializeCarousel(json.ImgLinks);
initializeAgent(json.Troubleshootings, json.TroubleshootingIDs);
}
function initializeCarousel(imgLinks) {
$('#ReasonVisualisation > ol').empty();
$('#ReasonVisualisation > .carousel-inner').empty();
for (var counter = 0; counter < Object.keys(imgLinks).length; counter++) {
$('#ReasonVisualisation > ol').append('<li data-target="#ReasonVisualisation" data-slide-to="' + counter + '"></li>');
$('#ReasonVisualisation > .carousel-inner').append('<div class="item"><img src="' + imgLinks[counter] + '"/> </div>');
}
$('#ReasonVisualisation > ol >li:first').addClass('active');
$('#ReasonVisualisation > .carousel-inner>div:first').addClass('active');
var list = $('#ReasonVisualisation > ol').html();
var inner = $('#ReasonVisualisation > .carousel-inner').html();
}
function initializeAgent(troubleshootings, ids) {
$('#Agent').empty();
for (var counter = 0; counter < Object.keys(troubleshootings).length; counter++) {
$('#Agent').append('<div>' + troubleshootings[counter] + ' </div>');
$('#Agent').append('<div class="btn AgentButton" id="q' + (counter * 2) + '">Yes</div>');
$('#Agent').append('<div class="btn AgentButton" id="q' + ((counter * 2) + 1) + '">No</div>');
agentButton = $('.AgentButton');
troubleshootingIDs[counter] = ids[counter];
}
}
function listDocuments(json) {
//Array.isArray(json);
if (json.length > 1) {
for (var counter = 0; counter < json.length; counter++) {
$('#DocList').append('<li> <a href=\"' + json[counter] + '\" > Link </a></li>');
}
}
}
}
);
The most interesting part are the first to methods within the script. In my provided code within the code I described my issue. I simply don´t why ajax reacts so different...
I use this method in my project, and it works.
But I dont know if it works to answer your problem.
JSFiddle Here
Change to "ajax": "/OverView/LoadProblems"
var problemTable = $("#ProblemTable").DataTable({
processing: true, // show message while querying fro data
serverSide: true,
"ajax": "/OverView/LoadProblems"
});
=========================================================================
$(".DeleteEntity").click(
function () {
try
{
var deleteTable = $("#DeleteTable").DataTable({
processing: true,
serverside: true,
destroy: true,
"ajax": "/Administration/ShowEntriesDelete"
});
}
catch (e)
{
console.log(e);
}
});
On my web page I used jquery and ajax to call a C# function to fill Dropdown list with respect to another
Dropdown Branch is filled as per the selection of zone and Employee with the selection of branch.It works perfect But the button Click is not working after this.Someone please tell me why this button click is not working??
[Button click works when no drop down selection is made]
my Code look Like this:
Jquery
<script src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('#<%= ddZone.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/BranchFill",
data: "{'Zone':'" + $("[id*=ddZone] option:selected").text() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlBranch = $("[id*=ddBranch]");
ddlBranch.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlBranch.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
$('#<%= ddBranch.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/EmployeeFill",
data: "{'Branch':'" + $(this).val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlEmployee = $("[id*=ddEmployee]");
ddlEmployee.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlEmployee.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
});
</script>
C#
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object BranchFill(string Zone)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Branch = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch(Zone, "", "SelectBranch");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Branch.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Code"].ToString()
});
}
return Branch;
}
else
{
return "false";
}
}
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object EmployeeFill(string Branch)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Employee = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch("", Branch, "SelectEmployee");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Employee.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Employee Id"].ToString()
});
}
return Employee;
}
else
{
return "false";
}
}
And the button Click(which is not working)
protected void Button1_Click(object sender, EventArgs e)
{
ReportClass RC = new ReportClass();
if (ddZone.SelectedValue !="0")
{
RC.Zone = ddZone.SelectedValue;
RC.Branch = ddBranch.SelectedValue;
RC.EmployeeId = ddEmployee.SelectedValue;
Report = RC.GetReport();
}
}
Why this click function is not Working, please help me to know..
Script codes:
<script type="text/javascript">
function drawVisualization01(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Class Average ');
data.addColumn('number', 'Score ');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value1, dataValues[i].Value2]);
}
var options = {
title: 'Topics Performance',
hAxis: { title: 'Topics', titleTextStyle: { color: 'red', fontSize: 15 }, textStyle: { fontSize: 12} },
vAxis: { format: '###.##%', textStyle: { fontSize: 12 }, maxValue: 1, minValue: 0 }
};
var formatter = new google.visualization.NumberFormat({ pattern: '###.##%' });
formatter.format(data, 1);
formatter.format(data, 2);
var chart_div01 = document.getElementById('visualization1');
var chart = new google.visualization.ColumnChart(chart_div01);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div01.innerHTML = '<img src="' + chart.getImageURI() + '">';
console.log(chart_div01.innerHTML);
var result = Foo(document.getElementById('<%=Textbox1.ClientID%>').value);
document.getElementById('<%=Textbox2.ClientID%>').value = chart.getImageURI();
});
chart.draw(data, options);
}
</script>
**JSON function**
<script >
function Foo(user_id) {
// Grab the information
var values = user_id;
var theIds = JSON.stringify(values);
// Make the ajax call
$.ajax({
type: "POST",
url: "ProgressReportNew.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: {ids: theIds },
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
}
</script>
[WebMethod]
public static void done(string ids)
{
String a = ids;
HttpContext context = HttpContext.Current;
context.Session["a"] = a;
}
C# code:
int t1 = Textbox1.Text.Trim().Length;
string as1 = (string)(Session["a"]);
Its brief code, I want convert the google chart to image in one click. Its my code ;from server side I want to pass the image base64 string, but unfortunately I am not getting into the text box; I tried using Ajax still it is not happening.
Can anyone help me to resolve this problem, before I used 2 button first to convert image and pdf it worked, but one button its not working.