嗨,我正在尝试通过视图模型将数据传递到局部视图以生成图形。
我在主视图中尝试了以下操作:
@{
ViewBag.Title = "Report";
}
@model WebApplication1.ViewModel.DatapointLineViewModel
我以这种方式将ViewModel传递给局部视图:
@{
Html.RenderPartial("~/Views/Shared/_report_bar.cshtml",WebApplication1.ViewModel.DatapointLineViewModel); }
我正在尝试通过Viewbags在ViewModel中使用数据:
labels: @Html.Raw(ViewBag.DataPoints),
我遇到以下错误:
CS0119:“ DatapointLineViewModel”是一种类型,在 给定上下文
这是我的视图模型:
[DataContract]
public class DatapointLineViewModel
{
public DatapointLineViewModel(string label, double y)
{
this.Label = label;
this.Y = y;
}
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "label")]
public string Label = "";
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "y")]
public Nullable<double> Y = null;
}
控制器:
public ActionResult BarChart()
{
List<DatapointLineViewModel> dataPoints = new List<DatapointLineViewModel>();
dataPoints.Add(new DatapointLineViewModel("USA", 71));
dataPoints.Add(new DatapointLineViewModel("Great Britain", 67));
dataPoints.Add(new DatapointLineViewModel("China", 70));
dataPoints.Add(new DatapointLineViewModel("Russia", 56));
dataPoints.Add(new DatapointLineViewModel("Germany", 42));
dataPoints.Add(new DatapointLineViewModel("Japan", 41));
//dataPoints.Add(new DatapointLineViewModel("France", 42));
//dataPoints.Add(new DatapointLineViewModel("South Korea", 21));
ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);
return View();
}
局部视图中的脚本:
data: {
labels: @Html.Raw(ViewBag.DataPoints),
datasets: [
{
label: 'My First dataset',
data: WebApplication1.ViewModel.DatapointLineViewModel,
options: {
legend: {
display: false
}
},
backgroundColor: [
'rgba(152,235,239,0.8)',
'rgba(152,235,239,0.8)',
'rgba(152,235,239,0.8)',
'rgba(152,235,239,0.8)',
'rgba(152,235,239,0.8)',
'rgba(152,235,239,0.8)'],
},
为什么会这样?需要帮助:)。
答案 0 :(得分:2)
您必须记住,此时要传递实际数据,而不是类型。
@{
Html.RenderPartial("~/Views/Shared/_report_bar.cshtml", Model);
}
Model
包含数据本身的实例,这就是您要传递给部分对象的内容。