我的网络应用程序是关于管理问题和答案的在线投票,我也可以对答案进行投票,所以现在我只需要在图形上显示每个答案的投票数量,我看到了< strong> Chart.js api所以我试图将它实现到我的应用程序,但在正确转换Json对象方面存在问题。
<html>
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js">
</script>
</head>
<body>
<div id="chart_container">
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar', data: {
labels: @Html.Raw(ViewBag.DataPoints)
datasets: [{
label: 'Numero de respostas',
data: @Html.Raw(ViewBag.DataPoints)
borderWidth: 1,
}]
},
options: {scales: {yAxes: [{ticks: {beginAtZero: true}}]}}});
</script>
</div>
这是我的控制器代码:
List<DataPoint> dataPoints = new List<DataPoint>();
foreach (var resposta in poolDbContext.Answers)
{
dataPoints.Add(new DataPoint(resposta.Text, answer.Votes.Count()));
}
ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);
ViewBag.Data = question.Answers;
ViewBag.ObjectName = question.Text;
这是我的DataPoint模型:
[DataContract]
public class DataPoint
{
public DataPoint(string labels, double data)
{
this.Label = labels;
this.Y = data;
}
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "labels")]
public string Label = "";
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "data")]
public Nullable<double> Y = null;
}
我设法让它显示正确数量的条形图,但它们没有值或答案文字
答案 0 :(得分:0)
我建议阅读堆栈溢出帮助部分,了解如何提问,如果您想在How to ask questions获得更多回复
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
</head>
<body>
<div id="chart_container">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<script>
var arrayOfAnswers = JSON.parse('@Html.Raw(Json.Encode(Model.Answers.ToList()))');
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: arrayOfAnswers,
datasets: [{
label: '# of Answers',
data: [//Enter data for all answers labels, corresponding to bars],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
</body>
</html>
这应该可行,你也不能在javascript数组中进行foreach
循环