-2

I´m trying to get some posts from the database. It works fine when opening in the posts index page but not in the main index. As a partialview, I have created a PostViewModel for the PostModel.

Here´s the code:

In Index.cshtml (Post):

@model IEnumerable<Project.Models.Post>

@foreach (var item in Model) { @item.Name }

In Index.cshtml (Main):

@model Project.Models.ViewModels.PostViewModel

@Html.Partial("~/Views/Posts/Index.cshtml", Model)

When I run the project, it complains about a System.NullReferenceException in the foreach loop.

How can I solve this problem?

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
  • Your code is supposed to be `@model IEnumerable` – Saravanan Jan 26 '17 at 16:09
  • I have it but for some reason does that part of the code not appear here – JaneTheDotNet Jan 26 '17 at 16:14
  • this part: @model IEnumerable – JaneTheDotNet Jan 26 '17 at 16:15
  • As a best practice you should check if model is not null before the for each loop. Also debug your controller to make sure you pass the data in the argument to the view. – Saravanan Jan 26 '17 at 16:18
  • Additionally ensure that the data type your passing to the view and the one in the partial view are same as the model – Saravanan Jan 26 '17 at 16:20
  • Please try to fix your title - is "partial view" and "partialview" the same? Please try to be consistent so that the quality of the questions does not suffer. Thanks and welcome. – Sabuncu Jan 26 '17 at 18:22
  • 1
    It looks like the data types are not the same. in Main/Index you are passing `Model` which is a `PostViewModel` into the Post/Index view, which is expecting a `collection of Post (eg. IEnumerable)`. – Sam Axe Jan 26 '17 at 19:37
  • http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Tieson T. Jan 26 '17 at 19:38
  • The code you have shown would throw a _The model item passed into the dictionary is of type .. but this dictionary requires a model item of type_ so you have not even shown the correct code. –  Jan 26 '17 at 21:28

2 Answers2

0

When you are passing Model from the main view to @Html.Partial it is not able to convert it to IEnumerable<Post> , which is expected by the partial view, that's why you see the NullReferenceException.

If you have a property in the PostViewModel class which is represents collection of Post then you should try passing that in the @Html.Partial

Let say you have a property Posts of type List<Post> in class PostViewModel then you should use it as following.

@Html.Partial("~/Views/Posts/Index.cshtml", Model.Posts)
Chetan
  • 6,711
  • 3
  • 22
  • 32
0

When the partial view is "called" the Model variable is internally set with

Model = instance as IEnumerable<Project.Models.Post>;

The instance you are passing is of type Project.Models.Post so it cannot be converted to IEnumerable<Project.Models.Post>. And that is the reason why Model is null inside the partial view.

Sir Rufo
  • 18,395
  • 2
  • 39
  • 73