【发布时间】:2019-02-01 21:17:57
【问题描述】:
大家好,我正在尝试通过视图模型将数据传递到局部视图以生成图表。
我在主视图中尝试了以下操作:
@{
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)'],
},
为什么会这样?需要帮助:)。
【问题讨论】:
-
如果主视图和局部视图中的模型都是
DatapointLineViewModel,那么它只是@{ Html.RenderPartial("_report_bar"); } -
@StephenMuecke 嗨,我尝试了同样的方法,但数据没有反映在部分视图中,因此尝试了这个。我哪里出错了? :)
-
你为什么使用
ViewBag- 你已经将模型传递给部分。而且您甚至没有显示将数据添加到ViewBag的位置和方式(以及DataPoints是什么?这是DatapointLineViewModel的属性吗? -
@StephenMuecke 嗨,刚接触这个并尝试一下,我相信我误解了某个概念,因此我附上了模型和控制器。我试图通过主视图将数据从控制器传递到局部视图中的脚本。你能指出我正确的方向吗:)
-
删除你
ViewBag.DataPoints并使用return View(dataPoints);。然后将其序列化为 javascript 数组,使用@Html.Raw(Json.Encode(Model)),
标签: c# asp.net .net model-view-controller asp.net-mvc-5