如何在单独的变量中分离标签和总值,然后返回视图,标签值显示在标签中,总值显示总计我正在显示一个代码,任何人都可以告诉我该怎么做。这是我的控制器和脚本,我正在使用chart.js我想将标签变量中的值标签值和总变量中的总值分开,这里是数组组合,表示组合中的标签和总值数组。
<script>
var myLabels = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.unitdata));
var myData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject());
var PieChartData =
{
labels: myLabels,
datasets: [{
label: 'ProductWise Sales Count',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data:myData
}]
};
window.onload = function () {
var ctx1 = document.getElementById("Piecanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'pie',
data: PieChartData,
options:
{
title:
{
display: true,
text: "ProductWise Sales Count"
},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>
public ActionResult Index()
{
MemberData();
return View();
}
[HttpPost]
public JsonResult MemberData()
{
List<object> unitdata = new List<object>();
unitdata.Add(new object[]
{
"Status", "Total"
});
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Sp_testing", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
con.Open();
using (SqlDataReader mReader = cmd.ExecuteReader())
{
while (mReader.Read())
{
unitdata.Add(new object[]
{
mReader["Status"], mReader["Total"]
});
}
}
con.Close();
}
}
return Json(unitdata);
}
您可以创建一个同时包含标签和数据 ViewModel 类:
public class ChartJsViewModel {
public List<object> unitdata {get; set;}
public List<object> labels {get; set;}
}
并像这样使用它:
[HttpPost]
public JsonResult MemberData()
{
List<object> unitdata = new List<object>();
List<object> labels = new List<object>();
// Populate the unitdata and labels from your database
.....
ChartJsViewModel chartModel = new ChartJsViewModel {
unitdata = unitdata,
labels = labels
};
return Json(chartModel);
}
然后,您可以在视图页面中反序列化图表模型 Json。
在视图上,您可以有类似的东西:
@model namespace.folder.ChartJsModelView
<div>
Chart JS Components
</div>
<script>
var myLabels = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(@Model.labels));
var myData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(@Model.unitdata));
/* Other chartjs script functions */
......
</script>