我正在做一个关于我在Twilio上的账户的项目。我想使用Chart.js库从我的控制台获取所有出站呼叫,并在环形图上显示它们的状态(已完成,无应答,忙碌,失败)。在运行调试时正确检索所有数据。唯一的问题是显示图表。
public async Task<IActionResult> GetAllCalls()
{
List<string> status = new List<string>();
ReceivedCallModel model = new ReceivedCallModel();
var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.twilio.com/2010-04-01/Accounts/{Account_Sid}/Calls.json?StartTime=2023-06-22");
var client = _httpClientFactory.CreateClient("MyClient");
HttpResponseMessage response = await client.SendAsync(request);
if(response.StatusCode == HttpStatusCode.OK)
{
var jsonString = await response.Content.ReadAsStringAsync();
model = JsonConvert.DeserializeObject<ReceivedCallModel>(jsonString);
foreach(var call in model.calls)
{
if(call.direction == "outbound-api")
{
status.Add(call.status);
ViewBag.States = status;
}
}
TempData["success"] = "Successful";
}
return View(model);
}
@model ReceivedCallModel
<div class="container">
<div class="row justify-content-center">
<div class="col-sm-6">
<div class="card border-0">
<div class="card-body">
<canvas id="chart">
</canvas>
</div>
</div>
</div>
</div>
</div>
@section Scripts{
<script type="text/javascript">
var canvaschart = document.getElementById("chart");
var completed = [];
var no_answer = [];
var busy = [];
var failed = [];
@if(TempData["success"] != null){
foreach(var item in ViewBag.States){
if(item == "completed"){
@: completed.push(@item);
}
else if(item == "no-answer"){
@: no_answer.push(@item);
}
else if(item == "busy"){
@: busy.push(@item);
}
else if(item == "failed"){
@: failed.push(@item);
}
}
}
const data = {
labels: [
'completed',
'no-answer',
'busy',
'failed'
],
datasets: [{
label: 'Call Status',
data: [completed.length, no_answer.length, busy.length, failed.length],
backgroundColor: [
'rgb(20, 205, 86)',
'rgb(54, 162, 235)',
'rgb(255, 205, 86)',
'rgb(255,0,0)'
],
hoverOffset: 4
}]
};
var barchart = new Chart(canvaschart, {
type: 'doughnut',
data: data
});
</script>
}
它成功地显示了TempData
值,而没有显示图表。
1条答案
按热度按时间xqnpmsa81#
您可以打开开发工具,您应该会看到以下错误:
这是因为你在js中调用C#的代码,你实际填入数组的是一个变量,而不是一个字符串:
您可以添加引号将其转换为字符串:
测试结果: