Click here to Skip to main content
15,893,190 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi. I have some queries that have some outputs in their select part. Now I want to send those queries outputs from controller into view but there is an error when sending them like the following:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1[Dashboard.Models.ChartModel]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.List`1[Dashboard.TempClasses.ChartListObjects]'.

for instance one of my query name is avg and to get its data, In controller there is a part of my code like the following:
part of my controller code
{

namespace Dashboard.Controllers
{
    public class HomeController : Controller
    {
    //    private readonly ILogger<HomeController> _logger;
        private readonly CSSDDashboardContext _context;
        public HomeController(DashboardContext context)
        {
            _context = context;
        }
     public IActionResult Index()  
    {
    var lstModel = new List<ChartModel>();

    var vm = new List<ChartListObjects>();
     foreach (var index in avg)
                {
                    lstModel.Add(new ChartModel
                    {
                        DimensionOne = index.Month,
                        Quantity = (int)index.Avg
                    });
                }
                vm.GrantedAvg = lstModel;

foreach (var index in grantedAccessPercent)
            {
                lstModel1.Add(new ChartModel
                {
                    DimensionOne = MonthName(index.Month),
                    Quantity = (int)index.pct
                });
            }
     vm.GrantedPercent = lstModel1;
    return view(vm);
    }
}




Here is my ChartModel class

namespace Dashboard.Models
{
    public class ChartModel
    {
        public int Quantity { get; set; }
        public string DimensionOne { get; set; }
    }
}


Here is my ChartListObjects class:

namespace Dashboard.TempClasses
{
    public class ChartListObjects
    {
        public List<ChartModel> GrantedPercent { get; set; }
        public List<ChartModel> AvgPercent { get; set; }

  }
}


I can't understand what is the problem, I appreciate of any help. Thanks.

What I have tried:

namespace Dashboard.Models
{
    public class ChartModel
    {
        public int Quantity { get; set; }
        public string DimensionOne { get; set; }
    }
}



And here is my part of view:

@using System.Linq;


@model List<Dashboard.TempClasses.ChartListObjects>
@{
    var XLabels = Newtonsoft.Json.JsonConvert.SerializeObject(Model.Select(x => x.GrantedPercent.FirstOrDefault().DimensionOne).ToList());
    var YValues = Newtonsoft.Json.JsonConvert.SerializeObject(Model.Select(x => x.GrantedPercent.FirstOrDefault().Quantity).ToList());
    ViewData["Title"] = "Pie Chart";
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Pie</title>
</head>
<body>
    <div class="box-body">

        <div class="chart-container">
            <canvas id="chart" style="width:100%; height:500px"></canvas>
        </div>
    </div>
</body>
</html>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script type="text/javascript">

                $(function () {
            var chartName = "chart";
                var ctx = document.getElementById(chartName).getContext('2d');
                var data = {
                        labels: @Html.Raw(XLabels),
                        datasets: [{
                            label: "Drinks Chart",
                            backgroundColor: [
                                'rgba(255, 99, 132, 0.2)',
                                'rgba(54, 162, 235, 0.2)',
                                'rgba(255, 206, 86, 0.2)',
                                'rgba(75, 192, 192, 0.2)',
                                'rgba(153, 102, 255, 0.2)',
                                'rgba(255, 159, 64, 0.2)',
                                'rgba(255, 0, 0)',
                                'rgba(0, 255, 0)',
                                'rgba(0, 0, 255)',
                                'rgba(192, 192, 192)',
                                'rgba(255, 255, 0)',
                                'rgba(255, 0, 255)'
                            ],
                            borderColor: [
                                'rgba(255,99,132,1)',
                                'rgba(54, 162, 235, 1)',
                                'rgba(255, 206, 86, 1)',
                                'rgba(75, 192, 192, 1)',
                                'rgba(153, 102, 255, 1)',
                                'rgba(255, 159, 64, 1)',
                                'rgba(255, 0, 0)',
                                'rgba(0, 255, 0)',
                                'rgba(0, 0, 255)',
                                'rgba(192, 192, 192)',
                                'rgba(255, 255, 0)',
                                'rgba(255, 0, 255)'
                            ],
                            borderWidth: 1,
                            data: @Html.Raw(YValues)
            }]
                    };

        var options = {
                        maintainAspectRatio: false,
                        scales: {
                            yAxes: [{
                                ticks: {
                                    min: 0,
                                    beginAtZero: true
                                },
                                gridLines: {
                                    display: true,
                                    color: "rgba(255,99,164,0.2)"
                                }
        }],
                            xAxes: [{
                                ticks: {
                                    min: 0,
                                    beginAtZero: true
                                },
                                gridLines: {
                                    display: false
                                }
                            }]
                        }
                    };

               var myChart = new  Chart(ctx, {
                        options: options,
                        data: data,
                        type:'pie'

                    });
                });
</script>
Posted
Updated 18-May-20 4:21am
v8

1 solution

Quote:
The model item passed into the ViewDataDictionary is of type List<ChartModel>, but this ViewDataDictionary instance requires a model item of type List<ChartListObjects>.
The error is quite clear - your view expects the model to be a list of ChartListObjects, but you have passed in a list of ChartModel objects.

This does not seem to match the code you've shown. Either the code you're running is not the code you've shown, or somewhere in your view you're rendering a partial view (with the Html.Partial helper, or the <partial> tag helper) and you're passing the wrong value to its model.

However, it's slightly confusing: your action uses ChartListObject, whereas your view and your class declaration use ChartListObjects. Those are two different class names. I don't know whether that's a typo in your code that's causing a build error, or a typo in your question.
 
Share this answer
 
Comments
ElenaRez 18-May-20 9:14am    
Thank you for your help. I want in the razor view to have list of ChartModels but I don't know how to fix this. Maybe even the class ChartListObjects is useless. Or maybe I need to know how to get those chartModels in View
Richard Deeming 18-May-20 9:18am    
If you want the view's model to be a List<ChartModel>, why have you declared it as a List<ChartListObjects>? And why are you passing a List<ChartListObject> (without the "s") from your action?
ElenaRez 18-May-20 10:22am    
Thanks. If you assume that grantedAccessPercent and Avg are two queries and I add their data into lstModel1 and lstModel respectively that are all kinds of ChartModel. How can I integrate them into an object and pass them from index method of Controller into view?
Richard Deeming 18-May-20 10:31am    
You create a class representing the data you want to pass to the view. You set the view's @model to match that class. Then you pass an instance of that class to the View method.

Eg:
public IActionResult Index()  
{
    var vm = new ChartListObjects
    {
        GrantedPercent = new List<ChartModel>(),
        AvgPercent = new List<ChartModel>(),
    };

    foreach (var index in avg)
    {
        vm.AvgPercent.Add(new ChartModel
        {
            DimensionOne = index.Month,
            Quantity = (int)index.Avg
        });
    }
    
    foreach (var index in grantedAccessPercent)
    {
        vm.GrantedPercent.Add(new ChartModel
        {
            DimensionOne = MonthName(index.Month),
            Quantity = (int)index.pct
        });
    }
    
    return View(vm);
}
View:
@model Dashboard.TempClasses.ChartListObjects
...
ElenaRez 18-May-20 14:39pm    
Thank you for your help. But then How can I get the ChartListObjects value? I wrote something like below but there is an error for DimensionOne and Quantity part like the following: 'List<chartmodel>' does not contain a definition for 'Quantity' and no accessible extension method 'Quantity' accepting a first argument of type 'List<chartmodel>' could be found (are you missing a using directive or an assembly reference?'

var XLabels = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedApiToApplicantAvg.DimensionOne).ToList();
var YValues = Newtonsoft.Json.JsonConvert.SerializeObject(Model.GrantedApiToApplicantAvg.Quantity).ToList();

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900