在MVC中創建和顯示圖表有很多種方法,你提到的鏈接是相當不錯的。我使用C#,但我做的方式是在視圖中使用IMG標記和SRC屬性指向一個控制器動作:
<img id="diagram" src="<%=Url.Action("DrawChartImage", "Home") %>" alt="Chart Diagram" />
控制器動作返回一個FileContentResult:
public ActionResult DrawChartImage()
{
using (var chartHelper = new ChartHelper())
{
//get data
var data = GetSomeDataForTheChart();
//draw chart
chartHelper.Draw(data);
//return chart as png image
return File(chartHelper.Image, "image/png");
}
}
的ChartHelper類實現了IDisposable並具有返回圖表作爲文件的輔助屬性(圖片),請注意,這只是示例/代碼片段展示了我的意思:
public class ChartHelper : IDisposable
{
private readonly Chart _chart;
public Chart Chart
{
get
{
return _chart;
}
}
public byte[] Image
{
get
{
using (var ms = new MemoryStream())
{
_chart.SaveImage(ms);
return ms.GetBuffer();
}
}
}
public ChartHelper()
{
_chart = new Chart();
_chart.Height = 300;
_chart.Width = 800;
_chart.ImageType = ChartImageType.Png;
_chart.Titles.Add("some title");
_chart.Legends.Add("some legend");
_chart.ChartAreas.Add("some chart area");
}
public void Draw(List<Data> data)
{
var dataArrays = GetDataArrays(data); //another helper method...
var series = new Series(tag);
series.Name = tag;
series.Legend = "tags";
series.ChartType = SeriesChartType.Spline;
series.BorderWidth = 4;
//sample way to add data below...
series.Points.DataBindXY(dataArrays.Item1, dataArrays.Item2);
_chart.Series.Add(series);
}
public void Dispose()
{
_chart.Dispose();
}
}
義和ks對我來說很好,希望它能幫助即使它在C#中。
編輯如果你想創建業務邏輯的圖像/圖表從你的「主」控制器動作叫,也許你可以做這樣的事情,你生成圖像/圖表,然後將其保存到磁盤,緩存或數據庫,並從所述圖像繪製控制動作把它撿起來:
public ActionResult Index()
{
//this is call to your business logic or similar which generates the chart
byte[] image = GenerateImage();
//save image to cache, disk or from database
HttpContext.Cache["image"] = image;
return View();
}
public ActionResult Image()
{
//get image from cache, disk or from database
var image = HttpContext.Cache["image"] as byte[];
return File(image, "image/png");
}
//some sample/dummy code to generate image from a template
private byte[] GenerateImage()
{
using (var ms = new MemoryStream())
{
using (var image = System.Drawing.Image.FromFile(@"c:/temp/template.png"))
using (var brush = new SolidBrush(System.Drawing.Color.Black))
using (var bmp = new System.Drawing.Bitmap(image, image.Width, image.Height))
using (var g = System.Drawing.Graphics.FromImage(bmp))
{
g.DrawString(DateTime.Now.ToLongTimeString(), new Font("Consolas", 10), brush, 10, 10);
bmp.Save(ms, ImageFormat.Png);
}
return ms.ToArray();
}
}
和視圖將是:
<img src="@Url.Action("Image")"/>
但它發送到另一個動作將需要沿着圖表數據傳遞。我在業務邏輯中有我的圖表邏輯,並且運行兩次會對應用程序的性能造成不良影響。我只需要在視圖上顯示圖表,當圖表已經在@ Model.Chart –
處創建時,我明白你的意思,在這種情況下,我將創建圖表並將其保存到磁盤或數據庫中作爲圖像業務邏輯中唯一的文件名或ID,然後在視圖中使用img-tag,並引用磁盤上的圖像或控制器/操作(如上面的示例),從數據庫中選取圖像並進行呈現。 –
添加了一些示例代碼,以顯示它如何做不同,希望它可以幫助:) –