I am trying to render a bar chart using Flot Chart JS. The data is dynamically change according to database. When I debug, the data is not rendered out. I tried to breakpoint in line(var data = strdata;) to find out what is going on with my data. End up the data only consists of one set of data value such as "[0, 5]". It seems like the strings are failed to join in the foreach loop.
Update: Ok. I have known that string cannot be concatenate within a loop. I have edited the action code and put my previous line in comment. The data and tick's content are correct but the chart is still without data.
Controller:
string strdata;
string strtick;
[HttpGet]
public ActionResult GetTestData()
{
string name;
int count;
int i = 0;
var list1 = dbContext.Collections.ToList();
foreach (Collection coll in list1)
{
name = coll.Name.ToString();
var list2 = dbContext.Item.Where(x => x.Name == name).ToList();
count = list2.Count();
displaydata = "[" + i + "," + collcount + "],";
displaytick = "[" + i + "," + collname + "],";
strdata += displaydata;
strtick += displaytick;
//strdata = string.Join(",", "[" + i + "," + count + "]");
//strtick = string.Join(",", "["+ i + "," +name+"]");
//i++;
}
var data = strdata;
var ticks = strtick;
var result = new {data = data, ticks = ticks };
return Json(result, JsonRequestBehavior.AllowGet);
}
View:
$.ajax({
type: "GET",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/Home/GetTestData/',
error: function () {
alert("An error occurred.");
},
success: function (data) {
//alert("Success.");
var dataset = [{ label: "2012 Average Temperature", data: [data.data], color: "#5482FF" }];
var ticks = [data.ticks];
var options = {
series: {
bars: {
show: true
}
},
bars: {
align: "center",
barWidth: 0.5
},
xaxis: {
axisLabel: "World Cities",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10,
ticks: ticks
},
legend: {
noColumns: 0,
labelBoxBorderColor: "#000000",
position: "nw"
},
grid: {
hoverable: true,
borderWidth: 2,
backgroundColor: { colors: ["#ffffff", "#EDF5FF"] }
}
};
$.plot($("#flot-dashboard5-chart"), dataset, options);
}
});
Related
I'm passing a list in JSON format from my controller, the data from the list is not being displayed in the view for some reason.
Here is the data being passed in controller:
[HttpPost]
public ActionResult GetIndustryCat(string Country)
{ var dataContext = MvcApplication.GetDataContext();
var Location = dataContext.Locations.Single(c => c.Location_Name == Country);
var IndustryCat = dataContext.IndustryCategories.Where(c => c.Location_ID == Location.Location_ID).ToList();
return Json(new {Cat = IndustryCat.Select(c => c.IndustryCategory_Name) });
}
Here is the view:
</select>
<script>
$("#selectindustrycat").hide();
$("select")
.change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.ajax({
url: "GetIndustryCat",
type: "POST",
data: { Country: str },
success: function (data) {
}
}).done(function (data) {
for (var i = 0; i < data.length; i++) {
$("#selectindustrycat").append('<option value=' + i + '>' + i + '</option>');
}
$("#selectindustrycat").show();
});
});
</script>
The selection option list displays but it has no data in it.
You need change from data to data.Cat
for (var i = 0; i < data.Cat.length; i++) {
$("#selectindustrycat").append('<option value=' + i + '>' + i + '</option>');
}
I'm having trouble with auto-search when I want to make two values
I want to search the store for product, please guide:
Controller
public JsonResult Search(string pr, string name, string model, string brand, string storename) {
var s = _context.Products.Where(a => a.Name.Contains(pr) || a.Model.Contains(pr) || a.Brands.Name.Contains(pr)).Select(a => new {
name = a.Name, model = a.Model, brand = a.Brands.Name
}).Take(10);
var storen = _context.Stores.Where(a => a.Name.StartsWith(pr)).Select(a => new {
storename = a.Name
});
return Json(new {
s,
storen
}, JsonRequestBehavior.AllowGet);
}
View
$(document).ready(function () {
var kam;
$("#CityName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/search",
type: "POST",
dataType: "json",
data: {
pr: request.term
},
success: function (data) {
response($.map(data, function (item) {
return [{
label: item.name + " " + item.model + " " + item.brand,
value: item.name + " " + item.model + " " + item.brand
}]
}))
}
})
},
messages: {
noResults: "",
results: ""
}
});
})
I think you want to combine both result sets to show into one Autocomplete widget. So for that, try to modify your code to look like this
Controller
public JsonResult Search(string pr) {
var s = _context.Products.Where(a => a.Name.Contains(pr) || a.Model.Contains(pr) || a.Brands.Name.Contains(pr)).Take(10).Select(a => new {
resultItem = a.Name + " " + a.Model + " " + a.Brands.Name
}).ToList();
var storen = _context.Stores.Where(a => a.Name.StartsWith(pr)).Select(a => new {
resultItem = a.Name
}).ToList();
var returnList = s.Concat(storen).ToList();
return Json(new {
returnList
}, JsonRequestBehavior.AllowGet);
}
This way your controller returns only one result set in json format.
View
$(document).ready(function () {
$("#CityName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Search",
type: "GET",
dataType: "json",
data: {
pr: request.term
},
success: function (data) {
response($.map(data, function (item) {
return [{
label: item.resultItem,
value: item.resultItem
}]
}))
}
})
},
messages: {
noResults: "",
results: ""
}
});
})
Note that I have changed the ajax request type to GET and label and value use the same resultItem field.
Instaed of:
var storen = _context
.Stores
.Where(a => a.Name.StartsWith(pr))
.Select(a => new { storename = a.Name });
Don't you want to use Contains, like in the first query ?
var storen = _context
.Stores
.Where(a => a.Name.Contains(pr))
.Select(a => new { storename = a.Name });
I am using chart.js to query sql server and display data on the chart. I have time interval on x-axis and on y-axis i have float data. chart is displaying nice but time interval is displaying continiously. I want time scale to be 30 minute interval and float to be 10.
<script type="text/javascript">
$(document).ready(function () {
$("#btn_line_chart").on('click', function () {
var mb_one = $("#ddl_one").val() + " " + $("#ddl_one_time").val();
var mb_two = $("#ddl_two").val() + " " + $("#ddl_two_time").val();
var jsonData = JSON.stringify({
mobileId_one: mb_one,
mobileId_two: mb_two
});
$.ajax({
type: "POST",
url: "sampleservice.asmx/getLineChartData",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(reponse) {
var aData = reponse.d;
var aLabels = aData[0];
var aDatasets1 = aData[1];
var aDatasets2 = aData[2];
var data = {
labels: aLabels,
datasets: [{
label: "My First dataset",
fill:false,
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
data: aDatasets1
},
{
label: "My Second dataset",
fill: false,
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
backgroundColor: "rgba(255,0,0,0.4)",
borderColor: "rgba(255,0,0,1)",
data: aDatasets2
}]
};
var ctx = $("#myChart").get(0).getContext('2d');
ctx.canvas.height = 300; // setting height of canvas
ctx.canvas.width = 300; // setting width of canvas
// var lineChart = new Chart(ctx).Line(data, {
// bezierCurve: false
// });//bezierCurve: false,
var lineChart = new Chart(ctx, {
type: "line",
data: data
});
}
function OnErrorCall_(repo) {
alert(repo.toString());
alert("Woops something went wrong, pls try later !");
}
});
});
// window.onload = function () {
// var ctx = document.getElementById("canvas").getContext("2d");
// window.myLine = new Chart(ctx).Line(lineChartData, {
// scaleOverride: true,
// scaleSteps: 10,
// scaleStepWidth: 50,
// scaleStartValue: 0
// });
// }
</script>
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.
When i am going to update data it alert me a error like "Status = Problem : Fail to Update Client Info". I have run this code without db.Update(ci); code, even without any update code it shows me "Successfully Updated.". But when i am used update method it is not executing. where is the problem i can not defined.... Here is my controller code..
public ActionResult Update(ClientInfo client, string id)
{
//Response.Write("Id : " + id + "<br>");
//Response.Write("Country : " + client.Country + "<br>");
try
{
//if (ModelState.IsValid)
//{
ClientInfo ci = db.Single<ClientInfo>("Where CId=" + id);
if (ci != null)
{
ci.CName = client.CName.ToString();
ci.CCName = client.CCName.ToString();
ci.Address = client.Address.ToString();
ci.PhoneNo = Convert.ToInt32(client.PhoneNo.ToString());
ci.Fax = client.Fax.ToString();
ci.Email = client.Email.ToString();
ci.Country = client.Country.ToString();
ci.PostalCode = Convert.ToInt32(client.PostalCode.ToString());
//ci.Update();
db.Update(ci);
return Json(new { msg = "Successfully Updated."});
}
else
return Json(new { msg = "Fail to Update Client Info." });
//}
//return RedirectToAction("Index");
}
catch
{
return Json(new { msg = "Problem : Fail to Update Client Info." });
}
}
And my script for post data to the server
$('#btnUpdate').click(function () {
var CId = $("#CId").val();
var CName = $("#CName").val();
var CCName = $("#CCName").val();
var PhoneNo = $("#PhoneNo").val();
var Fax = $("#Fax").val();
var Email = $("#Email").val();
var Address = $("#Address").val();
var PostalCode = $("#PostalCode").val();
var Country = $("#Country").val();
var client1 = {
"CId": CId,
"CName": CName,
"CCName": CCName,
"PhoneNo": PhoneNo,
"Fax": Fax,
"Email": Email,
"Address": Address,
"PostalCode": PostalCode,
"Country": Country
};
var lk = "/Clients/Update/" + CId;
//alert("Test : Update " + lk + "\n" + client1.Country);
client = JSON.stringify(client1);
$.ajax({
url: lk,
type: 'POST',
data: client,
dataType: "json",
success: function (data) {
alert("Status = " + data.msg);
},
error: function (data) {
alert("Error = " + data.msg);
}
});
You are not passing your data correctly. Your link is also incorrectly generated. Since you are passing two objects to your view, it's better to specify both in the ajax data object:
var lk = "/Clients/Update/"; // => removed the CId
//alert("Test : Update " + lk + "\n" + client1.Country);
client = JSON.stringify(client1);
$.ajax({
url: lk,
type: 'POST',
data: { client: client, id = CId } // => added an object containing all the expected parameters
dataType: "json",
success: function (data) {
alert("Status = " + data.msg);
},
error: function (data) {
alert("Error = " + data.msg);
}
});