This
article will show you how you can create a pie chart in mvc using razor view engine. This article we can use in MVC3, MVC4, MVC5, MVC6.
So for this
article first we will create a new asp.net mvc application, and add the model
class file.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
namespace
ChartDemoApplication.Models
{
public class ChartDataModel
{
public List<ChartData> ChartDataList
{ get; set; }
}
public class ChartData
{
public string CountryName { get; set; }
public int Population { get; set; }
}
}
|
After this
we will create a controller file and add the below code into the controller.
using
ChartDemoApplication.Models;
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace
ChartDemoApplication.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult
Index()
{
ChartDataModel
_ChartDataModel = new ChartDataModel();
_ChartDataModel.ChartDataList = new List<ChartData>();
_ChartDataModel.ChartDataList = ChartDate();
return
View(_ChartDataModel);
}
///
/// You can use your entity to
get the data
///
private List<ChartData> ChartDate()
{
List<ChartData> _ChartDataModel = new List<ChartData>();
_ChartDataModel.Add(new ChartData { CountryName = "India", Population = 125 });
_ChartDataModel.Add(new ChartData { CountryName = "Nepal", Population = 20 });
_ChartDataModel.Add(new ChartData { CountryName = "Sri Lanka", Population = 45 });
_ChartDataModel.Add(new ChartData { CountryName = "Rushia", Population = 60 });
return _ChartDataModel;
}
}
}
|
In above
code I have taken the model list and pass it to the view. Now we will create
the view and add the below code.
@model ChartDemoApplication.Models.ChartDataModel
@{
ViewBag.Title = "Chart (Pie Chart)
in MVC 5 Razor ";
}
<h2>Chart in MVC</h2>
@{
var filePathName = "~/_ChartFiles/chart01.jpg";
var displayPath = "_ChartFiles/chart01.jpg";
var myChart = new Chart(width: 500,
height: 300)
.AddTitle("Country
Population")
.AddSeries("Default", chartType: "Pie",
xValue: Model.ChartDataList, xField: "CountryName",
yValues: Model.ChartDataList, yFields: "Population");
// .Write();
myChart.Save(path: filePathName);
}
<img src="@displayPath" />
|
In above
code I have taken tow variable first for saving the chart image and second for
display the chart control.
Thank you. It helped.
ReplyDelete