HTML and CSS Reference
In-Depth Information
As you can see, the ChartMaster table stores the pie chart title and the physical image file URL. The
ChartDetails table stores sector information such as names, values, and colors. Although this application
doesn't regenerate charts based on stored data, you could easily do so because the data is readily available
in these tables.
MVC Controller
The ASP.NET MVC application has a single controller: ChartController . It contains code that saves a pie
chart as an image. It also saves the pie chart data into the ChartMaster and ChartDetails tables. The action
method of the ChartController class that does the job is shown in Listing 4-25.
Listing 4-25. Saving the Chart Image on the Server
[HttpPost]
public JsonResult SaveChart(string data, ChartMaster master, ChartDetail[] details)
{
Guid id = Guid.NewGuid();
string path = HttpContext.Server.MapPath("~/images/" + id.ToString() + ".png");
byte[] binaryData = Convert.FromBase64String(data);
FileStream file = new FileStream(path, FileMode.Create);
BinaryWriter bw = new BinaryWriter(file);
bw.Write(binaryData);
bw.Close();
ChartDbEntities db = new ChartDbEntities();
master.Id = id;
master.ImageUrl = "~/images/" + id.ToString() + ".png";
db.ChartMasters.AddObject(master);
foreach (ChartDetail detail in details)
{
detail.ChartId = master.Id;
db.ChartDetails.AddObject(detail);
}
db.SaveChanges();
return Json("Chart saved in the database!");
}
As you can see, the SaveChart() method accepts three parameters : canvas drawing data in Base64
format, a ChartMaster object, and an array of ChartDetail objects. These three parameters are sent from
the client-side jQuery code.
The code in SaveChart() should look familiar because previous sections have discussed these canvas-
saving techniques. Notice how a GUID serves dual purposes : acting as a chart ID and a physical file name.
The SaveChart() method essentially does two things: it saves the pie chart as a physical .png file on the
server and saves the chart data in the ChartMaster and ChartDetails tables. SaveChart() returns a success
message as a JsonResult object after a chart is saved on the server.
 
Search WWH ::




Custom Search