简体   繁体   中英

InvalidCastException: Unable to cast object of type 'CMP.Helpers.NavBarSettings' to type 'System.Collections.Generic.List`1[CMP.Helpers.NavBarItem]'

Hellow, I am trying to pass a List of objects to a view but I am stuck in this error.

Here is my code in the controller:

public IActionResult Index()
    {
        var Page = new PageSettings("HomeControllerIndex");
        ViewData["Page"] = Page;

        var NavBar = new NavBarSettings(Page.NavBar);
        ViewData["NavBar"] = NavBar;
        return View();
    }

The code in the view:

@using System.IO;
@using System.Reflection;
@using CMP.Helpers;
@{
    List<NavBarItem> Items = (List<NavBarItem>)ViewData["NavBar"];
}

@foreach (NavBarItem Item in Items)
{

}

Thanks for the comments, just made me look a litle more carefull to my solution, so here is the correct aproch:

public IActionResult Index()
    {
        var Page = new PageSettings("HomeControllerIndex");
        ViewData["Page"] = Page;

        var NavBar = new NavBarSettings(Page.NavBar);
        ViewBag.NavBar = NavBar;

        return View();
    }

@using System.IO;
@using System.Reflection;
@using CMP.Helpers;
@{
    var Items = (NavBarSettings)ViewData["NavBar"];
}

@foreach (NavBarItem Item in Items.NavBarItems)
    {

    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM