Hi guys I am trying to pass data through a view model to a partial view for it to generate a graph.
I tried the following in my main view:
@{
ViewBag.Title = "Report";
}
@model WebApplication1.ViewModel.DatapointLineViewModel
I am passing the ViewModel to the partial view in this manner:
@{
Html.RenderPartial("~/Views/Shared/_report_bar.cshtml",WebApplication1.ViewModel.DatapointLineViewModel); }
I am trying to use the data in the ViewModel through Viewbags:
labels: @Html.Raw(ViewBag.DataPoints),
I am getting the following error:
CS0119: 'DatapointLineViewModel' is a type, which is not valid in the given context
This is my View Model:
[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;
}
The controller:
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();
}
Script in partial 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)'],
},
Why is it so? Need Help:).
You have to remember you're wanting to pass actual data at this point, not a type.
@{
Html.RenderPartial("~/Views/Shared/_report_bar.cshtml", Model);
}
Model
contains the instance of the data itself, and this is what you're wanting to pass to the partial.
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.