如何在ASP.NET Core MVC中正确实现Chart.js?

huangapple go评论72阅读模式
英文:

How to implement Chart.js in ASP.NET Core MVC properly?

问题

以下是翻译的代码部分:

我正在处理一个关于我的 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>
}

这些是代码部分的翻译。如果需要进一步的帮助,请随时提出。

英文:

I'm working on a project regarding my account on Twilio. I want to get all the outbound calls from my console and show their status (completed, no-answer, busy, failed) on a doughnut chart using Chart.js library. All the data are retrieved correctly on running a debug. The only problem is with showing the chart.

public async Task&lt;IActionResult&gt; GetAllCalls()
{
List&lt;string&gt; status = new List&lt;string&gt;();
ReceivedCallModel model = new ReceivedCallModel();
var request = new HttpRequestMessage(HttpMethod.Get, $&quot;https://api.twilio.com/2010-04-01/Accounts/{Account_Sid}/Calls.json?StartTime=2023-06-22&quot;);
var client = _httpClientFactory.CreateClient(&quot;MyClient&quot;);
HttpResponseMessage response = await client.SendAsync(request);
if(response.StatusCode == HttpStatusCode.OK)
{
var jsonString = await response.Content.ReadAsStringAsync();
model = JsonConvert.DeserializeObject&lt;ReceivedCallModel&gt;(jsonString);
foreach(var call in model.calls)
{
if(call.direction == &quot;outbound-api&quot;)
{
status.Add(call.status);
ViewBag.States = status;
}
}
TempData[&quot;success&quot;] = &quot;Successful&quot;;
}
return View(model);
}
@model ReceivedCallModel
&lt;div class=&quot;container&quot;&gt;
&lt;div class=&quot;row justify-content-center&quot;&gt;
&lt;div class=&quot;col-sm-6&quot;&gt;
&lt;div class=&quot;card border-0&quot;&gt;
&lt;div class=&quot;card-body&quot;&gt;
&lt;canvas id=&quot;chart&quot;&gt;
&lt;/canvas&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
@section Scripts{
&lt;script type=&quot;text/javascript&quot;&gt;
var canvaschart = document.getElementById(&quot;chart&quot;);
var completed = [];
var no_answer = [];
var busy = [];
var failed = [];
@if(TempData[&quot;success&quot;] != null){
foreach(var item in ViewBag.States){
if(item == &quot;completed&quot;){
@: completed.push(@item);
}
else if(item == &quot;no-answer&quot;){
@: no_answer.push(@item);
}
else if(item == &quot;busy&quot;){
@: busy.push(@item);
}
else if(item == &quot;failed&quot;){
@: failed.push(@item);
}
}
}
const data = {
labels: [
&#39;completed&#39;,
&#39;no-answer&#39;,
&#39;busy&#39;,
&#39;failed&#39;
],
datasets: [{
label: &#39;Call Status&#39;,
data: [completed.length, no_answer.length, busy.length, failed.length],
backgroundColor: [
&#39;rgb(20, 205, 86)&#39;,
&#39;rgb(54, 162, 235)&#39;,
&#39;rgb(255, 205, 86)&#39;,
&#39;rgb(255,0,0)&#39;
],
hoverOffset: 4
}]
};
var barchart = new Chart(canvaschart, {
type: &#39;doughnut&#39;,
data: data
});
&lt;/script&gt;
}

It shows the TempData value successfully without showing the chart.

答案1

得分: 1

你可以打开开发者工具,你应该会看到这个错误:

这是因为你在js中调用了C#的代码,实际上在数组中填充的是一个变量,而不是一个字符串:

你可以添加引号将其转换为字符串:

@if (TempData[&quot;success&quot;] != null)
{
    foreach (var item in ViewBag.States)
    {
        if (item == &quot;completed&quot;)
        {
            @:completed.push(&#39;@item&#39;);
        }
        else if (item == &quot;no-answer&quot;)
        {
            @:no_answer.push(&#39;@item&#39;);
        }
        else if (item == &quot;busy&quot;)
        {
            @:busy.push(&#39;@item&#39;);
        }
        else if (item == &quot;failed&quot;)
        {
            @:failed.push(&#39;@item&#39;);
        }
    }
}

测试结果:

英文:

You can open the developer tools and you should see this error:
如何在ASP.NET Core MVC中正确实现Chart.js?

This is because you call the code of C# in js, what you actually fill in the array is a variable, not a string:
如何在ASP.NET Core MVC中正确实现Chart.js?

You can add quotes to convert it to a string:

@if (TempData[&quot;success&quot;] != null)
{
foreach (var item in ViewBag.States)
{
if (item == &quot;completed&quot;)
{
@:completed.push(&#39;@item&#39;);
}
else if (item == &quot;no-answer&quot;)
{
@:no_answer.push(&#39;@item&#39;);
}
else if (item == &quot;busy&quot;)
{
@:busy.push(&#39;@item&#39;);
}
else if (item == &quot;failed&quot;)
{
@:failed.push(&#39;@item&#39;);
}
}
}

Test Result:

如何在ASP.NET Core MVC中正确实现Chart.js?

如何在ASP.NET Core MVC中正确实现Chart.js?

huangapple
  • 本文由 发表于 2023年6月27日 17:35:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定