简体   繁体   中英

ASP.NET Core MVC - InvalidOperationException: The model item passed into the ViewDataDictionary is of type x

I'm getting the apparently classic exception:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'PieShop.ViewModels.HomeViewModel', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[PieShop.Models.Pie]'

when trying to render a page in ASP.NET Core MVC.

I've seen a lot of answers for this question, but all seem to be the result of an obvious datatype mismatch between what's passed into the view from the controller and what's declared in the view itself. In my case, they match perfectly. Here's my controller:

public class HomeController : Controller
{
    private readonly IPieRepository pieRepository;

    public HomeController(IPieRepository pieRepository)
    {
        this.pieRepository = pieRepository;
    }

    public IActionResult Index()
    {
        var pies = pieRepository.GetAllPies();

        var vm = new HomeViewModel()
        {
            SomeData = "haiod",
            Title = "Welcome to the Pie Shop"
        };

        return View(vm);
    }
}

Here's the view model:

public class HomeViewModel
{
    public string Title { get; set; }
    public string SomeData { get; set; }
}

And here's the view (which is called Views/Home/Index.cshtml :

@model PieShop.ViewModels.HomeViewModel

<h1>@Model.SomeData</h1>

The model passed into the view from the controller and what the view is declaring as its model are clearly the exact same type. What gives?

Turns out I had declared a type for the model in the shared _Layout.cshtml because I copy/pasted it during some refactoring:

@model IEnumerable<PieShop.Models.Pie>

So... just a copypasta error:facepalm:

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