Adding charts to views

By adding charts to your views, you can provide a rich experience for your users and the ability for them to receive an overall view of important information about the system.

There are a number of options when it comes to adding charts and graphs to your project; some of the most popular charting components are as follows:

Adding Google Charts to views

Google provides a rich charting API, which is powerful, easy to use, and free. They also provide an interactive gallery that showcases their many varieties of available charts.

In order to add Google Charts to the Index view of the Home controller, complete the following steps:

  1. Inside the Visual Studio Solution Explorer, double-click the Index.cshtml file inside the ViewsHome folder.
  2. Add a new Bootstrap row to the view, which will act as the container for the Google chart:
            <div class="row"> 
                <div class="col-md-6 col-sm-6" id="piechart">         
                </div> 
            </div> 
    
  3. Add a reference to the Google Charts library as well as a local JavaScript file to the bottom of the page:
            @section scripts{ 
                <script type="text/javascript" src="https://www.gstatic.com/charts        /loader.js"></script> 
                <script src="~/js/home.index.js"></script> 
            } 
    
  4. Next, add a new JavaScript file called home.index.js to the wwwrootjs folder.
  5. Add the following code to the home.index.js file, which will load the Google Charts API as well as specify the call-back function's name to run as soon as the API is loaded:
            google.charts.load('current', { 'packages': ['corechart'] }); 
            google.charts.setOnLoadCallback(generateChart); 
    
  6. Next, create the function called generateChart inside the file:
            function generateChart() { 
                var data = new google.visualization.DataTable(); 
                data.addColumn('string', 'Products'); 
                data.addColumn('number', 'Sales'); 
                data.addRows([ 
                  ['Tofu', 30], 
                  ['Chai', 10], 
                  ['Chocolade', 20], 
                  ['Ipoh Coffee', 40] 
                ]); 
     
                var options = { 
                    'title': 'Quarterly Sales', 
                    'width': 600, 
                    'height': 300, 
                    is3D: true, 
                    colors: ['#d9534f', '#f0ad4e', '#5bc0de', '#5cb85c'] 
                }; 
     
                var chart = new google.visualization.PieChart($('#piechart')[0]); 
                chart.draw(data, options); 
            } 
    

The code in the generateChart function creates a new DataTable class, which represents a two-dimensional table of values and adds two columns called Products and Sales to it by calling the addColumn method. Four rows of data, containing a product name and total number of products sold, are added to the DataTable class, using the addRows method.

Next, a new object called options is declared, which contains the options for the Google chart. In these options the colors for the title, size dimensions, and colors for the chart are specified. Setting the is3D option to true will generate the chart with a 3D effect.

A new pie chart is declared and its container element, which in this case is a <div> element with an id of piechart, is set. Finally, the chart is drawn by calling the draw method.

When running the project, the view should look similar to the following image:

Adding Google Charts to views

Server-side data processing with Google Charts

In the previous example, the data used for the pie chart was declared inside the JavaScript file. This approach is fine for static data, but in most scenarios you would want to read the data that is used to generate the charts from a data source such as a database.

In order to accomplish this, complete the following steps:

  1. Open the HomeController.cs file located in the Controllers folder.
  2. Add a new method called SalesPerSalesPerson that will return a JsonResult, as follows:
            [HttpPost] 
            public JsonResult SalesPerSalesPerson() 
            { 
                List<object> data = new List<object>(); 
                data.Add(new string[] { "Product", "Sales" }); 
                data.Add(new object[] { "Robert King",530}); 
                data.Add(new object[] { "Nancy Davolio", 1012 }); 
                data.Add(new object[] { "Laura Callahan", 810 }); 
                data.Add(new object[] { "Janet Leverling", 738 }); 
                return Json(data); 
            } 
    
  3. In the SalesPerSalesPerson method, a new List object is declared. The axis names are added as a string array, as well as the data for each sales person. This information could also have been read from a database.
  4. Next, open the Index.cshtml file in the ViewsHome folder and add the following HTML/Razor mark-up to the file:
            <div class="col-md-6 col-sm-6" id="barchart"                         
            data-dataurl="@Url.Action("SalesPerSalesPerson","Home")" 
            </div> 
    
  5. Note the <div> elements' data-dataurl attribute will be used in order to pass the URL of the action that will return the data for the chart to the JavaScript function.
  6. Open the home.index.js file and add the barChart JavaScript function:
            function barChart() { 
                var barChart = $('#barchart'); 
                var dataUrl = barChart.data('dataurl'); 
                $.post(dataUrl, function (d) { 
                    var data = google.visualization.arrayToDataTable(d); 
                    var chart = new google.visualization.BarChart(barChart[0]); 
     
                    var options = { 
                        'title': 'Sales per Representative', 
                        'width': 600, 
                        'height': 300 
                    }; 
                    chart.draw(data,options); 
                }); 
            } 
    
  7. Next, create a new generateChart function that will act as the callback function for the Google Chart API:
            function generateChart() { 
                pieChart(); 
                barChart(); 
            } 
    
  8. The pieChart method is the same code used in the previous example.

With the required code in place, you can run your project and the resulting view should contain a pie as well as a bar chart, as displayed in the following image:

Server-side data processing with Google Charts
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.124.194