The following code works but is hard-coded to a Guid (where it says "My Guid would be here").
VIEW
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">// <![CDATA[
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.post('/office/GetDivisions', { id: "My Guid would be here" },
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Stat');
tdata.addColumn('number', 'Total');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "Contracts"
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(tdata, options);
});
}
// ]]></script>
@model CMIS.Models.Divisions
<h1>Division</h1>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:300; height:300"></div>
CONTROLLER TO LOAD VIEW
public ActionResult Division(Guid id)
{
ViewBag.DivisionID = id; //the viewbag version
return View();
}
CONTROLLER METHOD CALLED BY JQUERY
public JsonResult GetDivisions(string id)
{
var myList = db.Database.SqlQuery<Dashboard>("EXEC [DBO].[uspDivisionDashboard2] {0}, {1}",
Environment.UserName, id).ToArray();
var data = myList.Select(x => new { Name = x.Stat, Value = x.Total }).ToArray();
return Json(data);
}
How can I replace the hard-coded Guid with something that comes from my controller?
I've passed a Guid to the model in various ways (Viewbag, a field) but haven't been able to replace that Guid string with this new source (Viewbag, a field) and have it work.
The use case here is that the user would see a grid listing Divisions and on clicking a link to one Division, I'd pass the DivisionID (in the query string for example) and show the Google chart for that Division.
MY FAILS
If I replace $.post('/office/GetDivisions', { id: "My Guid would be here" }, with $.post('/office/GetDivisions', { id: @ViewBag.DivisionID }, the controller code "GetDivision" is never executed.
Try using $.post('/office/GetDivisions', { id: "@ViewBag.DivisionID" }
instead, the problem is that quotes are missing.
I would also suggest changing the POST
request to GET
, as you are only retrieving data and not for example creating a new resource. See this post for a brief description of both HTTP methods.
To do so, you need to change the code in GetDivisions
from return Json(data);
to return Json(data, JsonRequestBehavior.AllowGet);
because the default behaviour of MVC is to not allow GET
requests by AJAX.
You should also make sure that the action is not decorated with the [HttpPost]
attribute.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.