ChartistJs : Create Responsive Charts in Asp.net C# [ Pie Chart, Donut Chart]

/ / 7 Comments

Responsive charts in Asp.net: This article explains how to create responsive charts in Asp.net C# with the database. For creating responsive charts, we are using Chartist.Js  a free javascript library. There is NO doubt that Responsive Web Design is very important for today’s Webdesign point of view. As Smartphone and tablet adoption rapidly increases, so does the importance of mobile-friendly websites. Creating Charts / Report is also a part in web applications.

So here we are going to demonstrate the using of Chartist.js in Asp.net Web form to create a beautiful responsive pie chart and donut chart with MS SQL server database connectivity.

About Chartist-Js:

Chartist-js is a simple responsive chart which provides highly customizable responsive chart options. The following facts should give you an overview of why to choose Chartists as your front-end chart generator:
  • Simple handling while using convention over configuration
  • Great flexibility while using a clear separation of concerns (Style with CSS & control with JS)
  • Usage of SVG (Yes! SVG is the future of illustration in the web!)
  • Fully responsive and DPI independent
  • Responsive configuration with media queries
  • Fully built and customizable with Sass.

Example:


So now using this awesome plugin we can create responsive charts in our Asp.net C# Web Application (Web forms).

Steps to create responsive charts in Asp.net C#

  1. Download and import Chartist-js library and CSS files.
  2. Create database .i.e table with some data.
  3. Add HTML Markup: Div tag where pie chart will display.
  4. Server-side code: Create a WebService (WebMethod) which returns data.
  5. Client-side code: Code to initialize Chartist-js and binding data, jQuery ajax call.
Let's head up to each method step by step for creating a responsive pie chart.

# Download and import Chartist-js library and CSS files.

Downloading Chartist-js (JS and CSS files) is very easy, you can download directly from Chartist-js official website or you can import from CDN jsdelivr.com.

Make sure after downloading import it into your Web Application. Also, add the latest jQuery library file. You can host the jQuery file on your server or you can also use from the Google-hosted site.

Now we are done with downloading so our webpage head tag looks like as shown below.

<head>
<link href="chartistJS/chartist.min.css" rel="stylesheet" />
<script src="chartistJS/chartist.min.js"></script>
<script src="latestJs_1.11/jquery.min.js"></script>
</head>

# Create database: Table with some data.

Here we are creating a pie chart which shows the total population location wise. So we have created a dummy table with data. In our database, we have a Table named as tb_city_population, and column as City_Name and Population have a look at table schema at Fig 1 and then added some data into our table as shown in Fig 2.

Fig 1:


Fig 2:


Database - add data to our table which is used to build responsive pie chart in Asp.net c#  


# Add HTML Markup: Div tag to display chart where pie chart will display.

Our responsive chart gets to display in Div tag, so first we add a Div tag. Then we add a drop-down list as we want to show the pie chart for the selected year from this drop-down selected value and a button.

On Button click event, we make a jQuery ajax call and then on its success method our responsive pie gets generated.

Finally, this is how our HTML looks like as written below:

 Select Year :
    <select id="ddlyear">
        <option>2010</option>
        <option>2011</option>
        <option>2012</option>
        <option>2013</option>
        <option>2014</option>
        <option selected="selected">2015</option>
    </select>
    <button id="btnCreatePieChart">Create Pie chart</button>
    <div class="ct-chart ct-golden-section"></div>
For better readability have modified default text color by adding below written CSS.
 .ct-label {
    color: white;
    fill: white;
    font-size: 0.75rem;
    line-height: 1;
}

Note: You can override default CSS and set your own custom styling as per your needs.

# Server-side code: Create a web service (WebMethod) which returns data.

Am assuming you are aware of creating Webservice and Webmethod. So first we add a web service in our application .i.e ( myWebService.asmx file), and then we write our WebMethod which returns JSON format data.

Finally, this is how our WebMethod looks like where its returns variable p having list object on citypopulation class.

//*
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
    List<cityPopulation> p = new List<cityPopulation>();

    using (SqlConnection cn = new SqlConnection(conn))
    {
        string myQuery = "SELECT top(5) id_, city_name, population FROM  tb_city_population WHERE  year_of = @year";
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = myQuery;
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@year", pData[0]);
        cmd.Connection = cn;
        cn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {
            while (dr.Read())
            {
                cityPopulation cpData = new cityPopulation();
                cpData.city_name = dr["city_name"].ToString();
                cpData.population = Convert.ToInt32(dr["population"].ToString());
                p.Add(cpData);
            }
        }
    }
    return p;
}

public class cityPopulation
{
    public string city_name { get; set; }
    public int population { get; set; }
    public string id { get; set; }
}
//*

Note: To avoid SQL Injections, I always use parameterized query or using Storedproceudre at my work. Check what is sql injection and how to prevent it? Best practice would be to use parameterized query to perform CRUD operations instead simple sql statement

# Client-side code: code to initialize Chartist-js and binding data (jQuery ajax call).

Now we do our client-side coding, we have already done with the server-side code by creating WebMethod which returns JSON format data. So now in our Ajax call on success will initialize Chartist-js variable. Client-side code looks like as written below
//*
$("#btnCreatePieChart").on('click', function (e) {
	  var self = $(this);
	  var pData = [];
	  pData[0] = $("#ddlyear").val();
	  var jsonData = JSON.stringify({ pData: pData });
	  $.ajax({
		  type: "POST",
		  url: "WebService.asmx/getCityPopulation",
		  data: jsonData,
		  contentType: "application/json; charset=utf-8",
		  dataType: "json",
		  success: OnSuccess_,
		  error: OnErrorCall_
	  });
	  function OnSuccess_(response) {
		  var aData = response.d;
		  var arrLabels = [], arrSeries = [];
		  $.map(aData, function (item, index) {
			  arrLabels.push(item.city_name);
			  arrSeries.push(item.population);
		  });
		  var data = {
			  labels: arrLabels,
			  series: arrSeries
		 }
                 // This is themain part, where we set data and create PIE CHART
		 new Chartist.Pie('.ct-chart', data);
	}
	  
	  function OnErrorCall_(response) {
	        alert("Whoops something went wrong!");
	  }
	  e.preventDefault();
});
//*
For Creating Responsive Donut Chart, we need to set a simple property .i.e donut=true. Code to display Donut Chart looks like as written below.
//*
new Chartist.Pie('.ct-chart', data, {
             donut: true
        });
//*
#Output:    We are done, this is how our pie chart looks.

#Conclusion:

Chartist-Js is an easy to use chart plugin and create responsive charts in our web application. In this article, we demonstrate with simple pie chart and donut chart, we can also create different kinds of charts like column, bar, line, area etc.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

7 Comments