The pie chart is failing to populate on the ASP.NET MVC webpage

I'm facing an issue with displaying data on my pie chart using Chart.js. The legend for the chart appears, but the values show up as undefined.

cshtml

@page
@model FinalProject.Pages.Exam.ReportModel
@{
    Layout = null;
}

<h2>Letter Grade Report</h2>
<table>
    <tr>
        <th>Exam ID</th>
        <th>Student ID</th>
        <th>Score</th>
        <th>Letter Grade</th>
    </tr>
    @foreach (var exam in Model.Exams)
    {
        <tr>
            <td>@exam.ExamId</td>
            <td>@exam.StudentID</td>
            <td>@exam.Score</td>
            <td>@FinalProject.Pages.Exam.ReportModel.CalculateLetterGrade(exam.Score)</td>
        </tr>
    }
</table>

<h2>Letter Grade Summary</h2>
<table>
    <tr>
        <th>Letter Grade</th>
        <th>Total Count</th>
    </tr>
    @foreach (var gradeSummary in Model.GradeSummary)
    {
        <tr>
            <td>@gradeSummary.LetterGrade</td>
            <td>@gradeSummary.TotalCount</td>
        </tr>
    }
</table>

<!-- Add Chart.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>

<h2>Letter Grade Distribution (Pie Chart)</h2>
<div style="max-height:300px;">
    <canvas id="gradeChart"></canvas>
</div>

<script>
    let gradeData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.GradeSummary));

    const data = {
        labels: gradeData.map(g => g.letterGrade),
        datasets: [{
            label: 'Grade Distribution',
            data: gradeData.map(g => g.totalCount),
            backgroundColor: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'],
            hoverOffset: 4
        }]
    };

    const config = {
        type: 'pie',
        data: data,
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    };

    new Chart(document.getElementById('gradeChart'), config);
</script>

cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;
using School.DAL;
using System;
using System.Collections.Generic;
using System.Linq;

namespace FinalProject.Pages.Exam
{
    public class ReportModel : PageModel
    {
        private readonly IExamAdapter _examAdapter;

        public ReportModel(IExamAdapter examAdapter)
        {
            _examAdapter = examAdapter;
        }

        public List<School.DAL.Exam> Exams { get; set; }
        public List<GradeSummary> GradeSummary { get; set; }

        public void OnGet()
        {
            Exams = _examAdapter.GetAll().ToList();

            // Calculate letter grades and generate summary
            GradeSummary = CalculateGradeSummary(Exams);
        }

        private List<GradeSummary> CalculateGradeSummary(List<School.DAL.Exam> exams)
        {
            var gradeSummary = new List<GradeSummary>();

            var gradeGroups = exams.GroupBy(e => CalculateLetterGrade(e.Score));

            foreach (var group in gradeGroups)
            {
                gradeSummary.Add(new GradeSummary
                {
                    LetterGrade = group.Key,
                    TotalCount = group.Count()
                });
            }

            return gradeSummary;
        }

        public static string CalculateLetterGrade(string score)
        {
            if (int.TryParse(score, out int scoreValue))
            {
                if (scoreValue >= 90) return "A";
                else if (scoreValue >= 80) return "B";
                else if (scoreValue >= 70) return "C";
                else if (scoreValue >= 60) return "D";
                else return "F";
            }
            else
            {
                // Handle the case where score is not a valid integer (e.g., invalid input)
                return "Invalid";
            }
        }
    }

    public class GradeSummary
    {
        public string LetterGrade { get; set; }
        public int TotalCount { get; set; }
    }
}

Here is what is currently shown:https://i.sstatic.net/JbqV5.png

I experimented with changing the script and considering the use of Adapters instead of my current method, but I believe it can be easily resolved. The dynamic data originates from CRUD operations on the website, specifically through actions like edit.cshtml, edit.cshtml.cs, delete.cshtml..., and this page serves the purpose of reporting and charting the exam scores.

Answer №1

After reviewing the Letter Grade Summary table, it has come to light that the properties follow Pascal's Case convention. However, in your JavaScript code, the properties are written in camel case. Due to the case sensitivity of these properties, the graph is not displaying correctly (resulting in labels showing as undefined).

Please update the properties to adhere to Pascal's Case format.

const data = {
    Labels: gradeData.map(g => g.LetterGrade),
    DataSets: [{
        Label: 'Grade Distribution',
        Data: gradeData.map(g => g.TotalCount),
        BackgroundColor: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'],
        HoverOffset: 4
    }]
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ASP.NET, utilizing Windows Authentication and the manipulation of querystrings

Situation: A website in ASP.NET C# is hosted on a Windows Server 2012 with SQL Server 2014. User authentication is done through Windows Authentication, configured in the web.config as follows: <authentication mode="Windows" /> <authorization> ...

Disabling Camera Dampening in a 3D Environment Upon Click

I am currently working on a project that involves implementing a damping effect for the camera when the user stops rotating it using their mouse. While this effect is important, I also want to provide users with the option to disable the damping effect by ...

Using a custom resolver in AutoMapper for the sub-entity

public class Vehicle { public int Identification {get;set;} public string Model {get;set;} public Driver DriverInformation {get;set} } public class Driver { public int LicenseNumber {get;set;} public string FullName {get;set;} publ ...

What exactly does Container-Based Authorization entail?

Did you know that the "XMLHttpRequest" object includes a method called "open," which has the option to supply a username and password? These parameters can be used for requests that require container-based authentication. Here is the method signature: op ...

JavaScript: Utilizing numbers to extend a sequence

My code is saved in a Google Sheets document and here is how it looks: ss = SpreadsheetApp.getActiveSpreadsheet(); function onOpen() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var menuEntries = [ {name: "10 Rows", functionName: "TenRows"}, ...

Adjusting the image in JavaScript and jQuery

Within a group of span elements, there are img tags nested inside. <span id = "span1" class="span-class"> <img src="img.jpg"/> </span> <!--Several more similar span elements --> <span id = "span123" class="span-class"> ...

What is preventing this AJAX request to the Controller from functioning on a specific page in Laravel?

I have encountered an issue with an Ajax call that seems to work on all pages except for the specific page where I need it to function. Below is the script in question: <script type="text/javascript"> var city = "مشهد"; $.ajax({ ...

How to display the date in Coordinated Universal Time (UTC) in an ASP.NET

I'm currently working on utilizing a GridView to display a DateTime value. My progress so far has allowed me to showcase the data with the desired format string by implementing: <asp:GridView ID="myGrid" ... > <Columns> <as ...

Unable to add selected item from dropdown menu to my database

Recently, I've been exploring C# and attempting to insert data into a database that I created within Visual Studio. -I'm working on developing a recipe application- In my form, there are various components such as text boxes for title, ingredien ...

Regular expression pattern for consistently capitalizing the phrases "CA" and "USA" in an address string

end_address = 'joe's home, 123 test avenue, los angeles, ca, usa 90210'; end_address = end_address.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); The outcome of this code will ...

Managing the storage and retrieval of dynamically generated PDF files within a SQL database

Exploring the realm of creating PDF documents for a current project has been an interesting journey. My goal is to save these generated PDFs in a SQL database and retrieve them when needed. I'm curious about the possibility of storing the document in ...

Are the frameworks Vue, Angular, and React known for

During a conversation, I came across an interesting viewpoint criticizing popular frameworks such as Angular, Vue, and React. It was argued that these frameworks have a significant disadvantage: apart from the API part that interacts with the server's ...

Tips for utilizing the chosen identification from a dropdown menu in Vue.js within a button located outside of the option/select tag iteration

I need to incorporate a button that can extract the id of the selected list of restaurants so that I can pass the id to my API request when the button is clicked. Unfortunately, I am facing difficulty in adding the button inside the select element as it di ...

Looking to expand my skills with AJAX. Can anyone recommend the best PDF or online resource for learning more about it?

Hello friends, I am a beginner in the world of ASP.NET and I have some knowledge about AJAX. However, I am eager to learn more about it. Can you please recommend me the simplest and best sources for information? Since I am new, it would be helpful if the s ...

Error occurred while trying to access a file within the server using $_GET method

Struggling to access a URL within my folder, but encountering an error. I have attempted using file_get_contents without success. Warning: include(/home/vol2_3/*****/*****/htdocs/new/td.php?r=8&ids=309834): failed to open stream: No such file or direct ...

Utilizing Html Agility Pack for extracting particular text snippets

Here is a snippet of Html code that I'm working with: <a href="https://secure.tibia.com/community/?subtopic=characters&name=Alemao+Golpista" >Alemao&#160;Golpista</a></td><td style="width:10%;" >51</td><td sty ...

"Code snippets customized for React are not functioning properly in the javascriptreact.json file within Visual Studio Code

I'm looking to incorporate some customized React.js code snippets into my Visual Studio Code setup. I am aware of the two files in VSCode that handle this - javascript.json and javascriptreact.json. Although the snippets work well in javascript.json, ...

Isotope Reference Error Uncaught

Currently attempting to implement a sortable menu using isotope. To simplify: <script scr="scripts/jquery.js"></script> <script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js"></script> < ...

Reduce the page zoom to 75% without changing the page layout

I am looking to implement a forced zoom out feature on a webpage, reducing the overall size to 75%. Unfortunately, I am unable to disclose the specific code as it belongs to the company I work for. Despite researching various methods online, including solu ...

Using Vue to store a variable amount of inputs within a dynamic two-dimensional array

My goal is to dynamically create text-fields based on the elements in a multi-dimensional array called response that I receive from the back-end. Each element in the response array contains inner elements like response[0][0] and response[0][1], which are o ...