Home > Enterprise >  MVC Error - The model item passed into the dictionary is of type
MVC Error - The model item passed into the dictionary is of type

Time:01-23

I'm getting this error in _GalleryImages.cshtml, and I'm passing the right Model.

The model item passed into the dictionary is of type 'PageContent.Models.Gallery', but this dictionary requires a model item of type 'Base.Models.Pagination'.

Gallery.cshtml

@using PageContent.Models
@model Gallery

<section>
 .
 .
 .
 @Html.Partial("~/Views/_GalleryImages.cshtml", Model)
</section>

_GalleryImages.cshtml

@using PageContent.Models
@using Base.Models
@model Gallery
@{
  Pagination pagination = Model != null ? Model.Pagination : null;
}
<section>
 .
 .
 .
 @Html.Partial("~/Views/_Pagination.cshtml", pagination)
</section>

_Pagination.cshtml

@using Base.Models
@model Pagination

<section>
 .
 .
 .    
</section>

Gallery.cs

namespace PageContent.Models
{
    using Base.Models;
    public class Gallery
    {
        public Pagination Pagination {get; set;}
    }
}

Pagination.cs

namespace Base.Models
{
    public class Pagination
    {
    }
}

I tried passing Model.Pagination like this

@Html.Partial("~/Views/_Pagination.cshtml", Model.Pagination)

But it did not work. So, assigned this to a variable inside the view and no luck with that too.

CodePudding user response:

EDIT: For clarification, that error just means that your view is expecting a ModelX but you are trying to instantiate it with a ModelY instead. So basically you just have to ensure that you are passing the correct Model to the correct View.

Modify your _GalleryImages.html as followed

@using PageContent.Models
@using Base.Models
@model Gallery

@{
  Pagination pagination = Model != null ? Model.Pagination : null;
}

<section>
 .
 .
 .
 @Html.Partial("~/Views/_Pagination.cshtml", pagination)
</section>

You can use @{ ... } to define your variables. If you want to use a model value you will have to write Model.Value instead of just passing the parameter; you will be obtaining the value from inside your Model.

On a side note, you should populate your model from your controller instead of assigning values inside the view. Then as mentioned before just pass the values using the Model. prefix. ie; @Html.Partial("~/Views/_Pagination.cshtml", Model.Pagination).

CodePudding user response:

The issue was with the Model.Pagination. It was being passed as null. The MVC error was misleading.

  • Related