skip to Main Content

I am working on a project to create Bar charts where in X Axis we dynamically display the Agent Names and their respective Deal status.

So in bar chart we call the data from db and display the values on the Bar chart. So far I have been able to successfully call first set of data which is Deals Open, In Progress and Cancel. However the issue I am facing with passing the Agent Name on X Axis dynamically.

In my below code for now I have simply hardcoded the names but I want it should be able to be displayed from db and not hard coded, and also should display agents respective Deals.

Here is my code:

public class ReportVM
{
    public string AgentName { get; set; }

    public int OpenClient { get; set; }
    public int ClosedClient { get; set; }
    public int InProgressClient { get; set; }
    public int CancelClient { get; set; }
}

Controller where I am storing the list in a ViewBag:

var thisWeekAgentPerform = db.Clients.Where(x => DbFunctions.TruncateTime(x.CleitnCreatedDate) >= thisWeekMonday
                                && DbFunctions.TruncateTime(x.CleitnCreatedDate) <= thisWeekSunday)
                                .GroupBy(c => c.AgentUname //this AgentName is from Client Model Class
                                ).Select(b => new ReportVM()
                                {
                                    AgentName = b.Key, //this AgnetName is from Report VM
                                    OpenClient= b.Count(),
                                    ClosedClient = b.Count(),
                                    InProgressClient = b.Count()
                                }).ToList();
ViewBag.AgentThisWeekPerform = thisWeekAgentPerform;

View

<div class="chart">
<canvas id="barchart"></canvas>
</div>

jQuery

var barCanvas = document.getElementById("barchart");
debugger;
    
var OpenClient = [];//these are all javascript array variables

var ClosedClient = [];
var InProgressClient = [];
var AgentName = []
    
@if (ViewBag.AgentThisWeekPerform.Count > 0)
{
    foreach (var item in ViewBag.AgentThisWeekPerform)
    {
        @:OpenClient.push(@item.OpenClient);
        @:ClosedClient.push(@item.ClosedClient);
        @:InProgressClient.push(@item.InProgressClient);
        @:AgentName.push(@item.AgentName);
    }
}

var OpenClient = {
                     label: 'OpenClient',
                     data: OpenClient,
                     backgroundColor: 'rgb(255, 99, 132)',
                     borderWidth: 0,
                     lineTension: 0,
                 };
var ClosedClient = {
                       label: 'ClosedClient',
                       data: ClosedClient,
                       backgroundColor: 'rgb(54, 162, 235)',
                       borderWidth: 0,
                   };
    
var InProgressClient = {
                           label: 'InProgressClient',
                           data: InProgressClient,
                           backgroundColor: 'rgb(157, 230, 41)',
                           borderWidth: 0,
                       };

var datasetvalues = {
            labels: [AgentName],//x-axis label values (HERE I WANT TO PASS NAMES DYNAMICALLY)
            datasets: [OpenClient, ClosedClient, InProgressClient]//y-axis
        };
    
var chartOptions = {
            scales: {
                xAxes: [{
                    barPercentage: 1,//Percent (0-1) of the available width each bar should
                    categoryPercentage: 0.6,//Percent (0-1) of the available width each category
                }],
                yAxes: [{
                    barPercentage: 1,
                    categoryPercentage: 0.6,
                    ticks: {
                        beginAtZero: true
                    }
                }],
       }
};

var barChart = new Chart(barCanvas, {
       type: 'bar',
       data: datasetvalues,
       options: chartOptions
});

Bar graph result
Thank you in advance.

2

Answers


  1. In addition to changing labels: [AgentName] to labels: AgentName (you need only 1 dimensional array for labels), you might need to change also this line

    @:AgentName.push(@item.AgentName);
    

    I believe, you need additionally wrap it with string quotes like this

    @:AgentName.push('@item.AgentName');
    

    So instead of AgentName.push(John) you will actually insert a string into the array: AgentName.push('John')

    Login or Signup to reply.
  2. Change labels: [AgentName] to labels: AgentName and be sure add ” surround the @item.AgentName. You also need modify the datasets for y-axis like below:

    <div class="chart">
        <canvas id="barchart"></canvas>
    </div>
    
    @section Scripts {
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
        <script>
            var OpenClient = [];
            var ClosedClient = [];
            var InProgressClient = [];
            var AgentNames = [];    
            @if (ViewBag.AgentThisWeekPerform != null && ViewBag.AgentThisWeekPerform.Count > 0)
            {
                foreach (var item in ViewBag.AgentThisWeekPerform)
                {
                    @:OpenClient.push(@item.OpenClient);
                    @:ClosedClient.push(@item.ClosedClient);
                    @:InProgressClient.push(@item.InProgressClient);
                    @:AgentNames.push('@item.AgentName');   //add '' surround the @item.AgentName
                }
            }
                 
             var datasetvalues = {
                labels: AgentNames, // X-axis agent names dynamically
                datasets: [           //y-axis
                    {
                        label: 'Open Deals',
                        data: OpenClient,
                        backgroundColor: 'rgb(255, 99, 132)',
                        borderWidth: 1
                    },
                    {
                        label: 'Closed Deals',
                        data: ClosedClient,
                        backgroundColor: 'rgb(54, 162, 235)',
                        borderWidth: 1
                    },
                    {
                        label: 'In Progress Deals',
                        data: InProgressClient,
                        backgroundColor: 'rgb(75, 192, 192)',
                        borderWidth: 1
                    }
                ]
            };
    
            // Chart options
            var chartOptions = {
                scales: {
                    x: {
                        beginAtZero: true,
                        barPercentage: 0.6
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                },
                responsive: true
            };
    
            // Render bar chart
            var ctx = document.getElementById("barchart").getContext("2d");
            var barChart = new Chart(ctx, {
                type: 'bar',
                data: datasetvalues,
                options: chartOptions
            });
        </script>
    }
    

    Result:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search