1

Hi everyone I am building an application that allows the users to submit posts and I am trying to use orderby on a list in ascending order but I get this error

Error

The model item passed into the dictionary is of type 'System.Linq.OrderedEnumerable'2[myproject.Models.NewsPostVM,System.Nullable'1[System.Int32]]', but this dictionary requires a model item of type 'System.Collections.Generic.List'1[myproject.Models.NewsPostVM]'. Controller

public ActionResult News()
{
    var posts = db.NewsPosts.Select(d => new NewsPostVM()
    {
        ID = d.ID,
        Heading = d.Heading,
        Body = d.Body,
        Images = d.Images.Select(i => new NewsImageVM()
        {
            Path = i.Path,
            FileName = i.DisplayName
        }).ToList()
    }).ToList();
    var post= posts.OrderBy(m => m.ID);
    return View(post);
}

view

@model List<MyProject.Models.NewsPostVM>
@foreach (var p in Model)
{
    <div class="w3-container w3-center">
        <h5><b>@p.Heading</b></h5>
        <p>@p.Body</p>
        @foreach (var image in p.Images)
        {
            <img class="img-thumbnail" width="150" height="150" src="~/Images/@image.Path" />
        }
        <h6>@p.Date</h6>
    </div>
}
  • 2
    Either change your model definition to accept IEnumerable `@model IEnumerable` or add `ToList()` to return a list from your _controller_ like this: `var post= posts.OrderBy(m => m.ID).ToList();` – Rahul Singh Feb 03 '17 at 12:01
  • Use `var posts = db.NewsPosts.OrderByx => x.ID).Select(d => new NewsPostVM() { ... }).ToList();` and delete `var post= posts.OrderBy(m => m.ID);` - its more efficient that the answers (but do not use `var` and it would have been obvious) –  Feb 04 '17 at 06:24

2 Answers2

3

You have to call ToList on your model data before assigning it:

var post= posts.OrderBy(m => m.ID).ToList();
return View(post);

Alternative you could change Model for your view to accept IEnumerable (if you are just going with foreach through it, IEnumerable is ok):

@model IEnumerable<MyProject.Models.NewsPostVM>
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
0

Because you are using 'var' as the variable type, the compiler chooses IOrderedEnumerable to be the best suitable type. However your view expects a list.

use 'ToList' to force the result to be a list:

var post= posts.OrderBy(m => m.ID).ToList();

You can avoid this unexpected behaviour by specifying your variable types like:

IList<NewsPostVM> posts = posts.OrderBy(m => m.ID).ToList();
middelpat
  • 2,555
  • 1
  • 20
  • 29
  • 2
    you couldn't jsu assign IEnumerable to List, your second line won't compile – Maksim Simkin Feb 03 '17 at 12:07
  • You're correct. Changed it to use .ToList() as well. This is a little bit more code, but ensures that variable types don't 'magically' change for newer users. – middelpat Feb 03 '17 at 12:32