Thursday, 11 May 2017

Using Chart control in ASP.Net MVC Razor

chart control in mvc

Description:
In this example we explain that how to use chart control in asp.net MVC or how to display chart in MVC or drawing chart into asp.net MVC or displaying data in chart with Asp.Net Razor in MVC. how to display or bind chart in razor view in asp.net MVC. There are many question are raised for binding chart in mvc.so how to use chart control to create or display chart in asp.net MVC razor view.

Here we create chart or bind chart data from database using charts helper class in asp.net MVC Razor. so how to use charts helper class in asp.net razor to display or bind chart in MVC.

Here we demonstrate how to bind charts from the database using charts helper class in asp.net MVC.
Controller:
public ActionResult Index()
{
    string query = "SELECT LeadSource, COUNT(LeadId) TotalLead";
    query += " FROM Lead WHERE Priority = 'High' GROUP BY LeadSource";
    string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
    List<LeadModel> chartData = new List<LeadModel>();

    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 LeadModel
                    {
                        LeadSource = sdr["LeadSource"].ToString(),
                        TotalLead = Convert.ToInt32(sdr["TotalLead"])
                    });
                }
            }

            con.Close();
        }
    }

    return View(chartData);
}

View:

@model List<Charts_MVC.Models.LeadModel>

@{
    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("USA City Distribution")
       .AddSeries("Default", chartType: "Pie",
            xValue: Model, xField: "LeadSource",
            yValues: Model, yFields: "TotalLead")
        .Write();
    }
</body>
</html>



This entry was posted in :

0 comments:

Post a Comment