Description:
Model:
In this example
we explain that how to display Bar Charts from Database using Chart Helper in
Asp.Net MVC.or how to bind Charts from database using MVC.or how to bind or
populate Bar Charts in Razor View in MVC.
Here in this example
we explain that how to create Charts from database using charts Helper class in
MVC Razor.
public class OrderModel
{
public string StateName { get;
set; }
public int TotalOrders { get;
set; }
}
Controller:
public ActionResult Index()
{
string
query = "SELECT StateName, COUNT(orderid) TotalOrders";
query += "
FROM Orders WHERE StateName = 'INDIA";
string
Connectionstring = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
List<OrderModel> chartData = new List<OrderModel>();
using (SqlConnection con = new
SqlConnection(Connectionstring))
{
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 OrderModel
{
StateName = sdr["StateName"].ToString(),
TotalOrders = Convert.ToInt32(sdr["TotalOrders"])
});
}
}
con.Close();
}
}
return
View(chartData);
}
View:
@model List<Charts_MVC.Models.OrderModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Create
Charts (Bar Charts) from Database using Charts Helper in ASP.Net MVC</title>
</head>
<body>
@{
var chart = new Chart(width: 500,
height: 500, theme: ChartTheme.Yellow)
.AddTitle("Total Order By State of
India")
.AddSeries("Default",
chartType: "Bar",
xValue: Model, xField:
"StateName",
yValues: Model, yFields:
"TotalOrders")
.Write();
}
</body>
</html>
0 comments:
Post a Comment