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

Model

Add below code in BarModel.cs

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

 Controller

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;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            chartData.Add(new City
                            {
                                CityName = sdr["CityName"].ToString(),
                                TotalCities = Convert.ToInt32(sdr["TotalCities"])
                            });
                        }
                    }

                    con.Close();
                }
            }

            return View(chartData);
        }

View

@model List<Bar_chart.Models.City>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @{
        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")
        .Write();
    }
</body>
</html>

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

Output

Bar chart