Stan
Stan

Reputation: 26511

Pass tuple with two object collections to view?

I want to pass two collections of objects. First is Post, second is Gallery. However I get error and I don't know how to fix this.

I've done this when passing two single objects and it is working fine, but now I need to pass two collections of those objects and it gives me error.

Error

The model item passed into the dictionary is of type 'System.Tuple2[System.Linq.IQueryable1[photoBlog.Models.Gallery],System.Linq.IQueryable1[photoBlog.Models.Post]]', but this dictionary requires a model item of type 'System.Tuple2[System.Collections.Generic.IEnumerable1[photoBlog.Models.Gallery],System.Collections.Generic.IEnumerable1[photoBlog.Models.Post]]'.

Controller

public ActionResult Index()
{
    photoBlogModelDataContext _db = new photoBlogModelDataContext();
    var posts = _db.Posts.OrderByDescending(x => x.DateTime).Take(4);
    var galleries = _db.Galleries.OrderByDescending(x => x.ID).Take(4);
    return View(Tuple.Create(galleries, posts));
}

View

@model Tuple<IEnumerable<photoBlog.Models.Gallery>, IEnumerable<photoBlog.Models.Post>>
@foreach (var item in Model.Item1)
{
   @item.Name
}

Upvotes: 0

Views: 10948

Answers (3)

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

Just try this

var posts = _db.Posts.OrderByDescending(x => x.DateTime).Take(4).ToList();
var galleries = _db.Galleries.OrderByDescending(x => x.ID).Take(4).ToList();

Upvotes: 0

I think you should modify your controller method to this:

public ActionResult Index()
{
    photoBlogModelDataContext _db = new photoBlogModelDataContext();
    var posts = _db.Posts.OrderByDescending(x => x.DateTime).Take(4).ToArray();
    var galleries = _db.Galleries.OrderByDescending(x => x.ID).Take(4).ToArray();
    return View(Tuple.Create(galleries, posts));
}

From your error message, it appears that the queries are not resolved yet when your view is rendered. By also doing ToArray or ToList, you will force the query to hit the database before you return from the controller method.

Upvotes: 4

Mihai Labo
Mihai Labo

Reputation: 1082

You need to create a new Entity in your domain.Model

Here is an example I provided today : MVC3: button to send both form (model) values and an extra parameter
Later Edit :

namespace App.Domain.Model
{
    public class Tuple
    {
        public IEnumerable<photoBlog.Models.Gallery> Gallery{ get; set; }
        public IEnumerable<photoBlog.Models.Post> Post{ get; set; }
    }
}

you will send the Tuple object to your view as follows :

@model: (Domain.Model.)Tuple  <--- (your exact model path )
@foreach (var item in Model.Gallery)
{
   @item.Name
}

Another posibility would be using viewbag ... but i strongly suggest you do it the correct way,i.e. the MVC way

Upvotes: 1

Related Questions