Display Bar chart in MVC using chart helper

Display Bar chart in MVC using chart helper. Data is retrieve from database. In this article   the list of all cities in the State is displayed using charts.

Download Script here


Add below code in BarModel.cs

public class City
    public string CityName { get; set; }
    public int TotalCities { get; set; }


Below code is added in BarController. The connection string used in the code is taken from web.config file -> App settings.

public ActionResult Index()
            string query = "SELECT City as CityName,COUNT(ID) TotalCities FROM CountryDetails WHERE Name = 'India' Group by City";
            string constr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
            List<City> chartData = new List<City>();

            using (SqlConnection con = new SqlConnection(constr))
                using (SqlCommand cmd = new SqlCommand(query))
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                        while (sdr.Read())
                            chartData.Add(new City
                                CityName = sdr["CityName"].ToString(),
                                TotalCities = Convert.ToInt32(sdr["TotalCities"])


            return View(chartData);


@model List<Bar_chart.Models.City>
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width"/>
        var chart = new Chart(width: 500, height: 500, theme: ChartTheme.Yellow)
       .AddTitle("Distribution of countries in India")
       .AddSeries("Default", chartType: "Bar",
            xValue: Model, xField: "CityName",
            yValues: Model, yFields: "TotalCities")

In the above code the user can change the Chart type to display different chart types like “Bar”,”Line” and “Pie” charts.


Bar chart