[英]working with strongly typed data in Javascript
我在Razor中使用asp.net我有一個返回return View(db.sales.ToList())的控制器;
我的模特是
public class sales
{
public int ID { get; set; }
public string month { get; set; }
public int sale {get;set;}
}
我的觀點得到了
@model IEnumerable<salesmonths.Models.sales>
我正在使用Javascript創建圖表,如何將月份提取到字符串表中,將銷售額提取到int表中
這是圖表腳本
<script>
var barChartData = {
labels : ["January"],/// i want to place the month table here
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
data : [28,48,40,19,96,27,100] /// and the sale table here
}
]
}
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);
</script>
頁面完成加載到控制器操作方法后,您可以進行ajax調用,以JSON格式獲取數據並使用它來構建圖表。 大多數圖表庫都接受JSON格式的數據作為繪制圖表的輸入。
$(function(){
$.getJSON("@Url.Action("Sales","Home")",function(response){
//JSON data is in "response" variable now.
});
});
假設當調用來自ajax請求時,您的Action方法返回JSON表示形式。 您可以使用Request.IsAjaxRequest
方法確定該請求是來自ajax請求還是正常的http請求。
public ActionResult Sales()
{
var saleListVM=new List<salesmonths.Models.Sales>();
// to do :Load data to the list
if(Request.IsAjaxRequest())
{
return Json(saleListVM,JsonRequestBehaviour.AllowGet);
}
//not an ajax request- let's return the view model the normal view
return View(saleListVM);
}
因此,當用ajax請求調用時,此操作方法將返回數據的JSON表示形式,如下所示。
[
{ "ID": 0, "month": "Jan", "sale": 134 },
{ "ID": 0, "month": "FEb", "sale": 534 }
]
現在,在getJSON方法的回調中,您可以遍歷數組中的項目並將其設置為圖表的“選項”。 $(函數(){
$.getJSON("@Url.Action("Sales","Home")", function (response) {
var salesLabels = [];
var salesData = [];
//Let's loop through the items in array and add to our temp array
$.each(response, function (index, item) {
salesLabels.push(item.month);
salesData.push(item.sale);
});
var barChartData = {
labels: salesLabels,
datasets: [
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,1)",
data: salesData
}
]
};
var myLine=new Chart(document.getElementById("canvas").getContext("2d"))
.Bar(barChartData);
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.