views:

488

answers:

4

I have a View strongly typed to an Item class. In my controller I need to send two different List. Is there an easier way to do this other than creating a new class with two List.

What I am ultimately trying to do is have on my homepage 10 items ordered by Date, and 10 items ordered by Popularity.

WHAT I DID

I actually went with a combination of the two answers. I strongly-typed my View to the new class I created with the two lists. I then strongly-typed two partial views to the each one of the lists. May seem like overkill, but I like how it turned out.

+10  A: 

"creating a new class with two Lists" is the way to go. It's called a view model and once you embrace it, the power of strongly-typed views really opens up. It can be this simple:

public class IndexViewModel 
{
    public List<Item> Newest { get; set; }
    public List<Item> Popular { get; set; }
}
John Sheehan
+3  A: 

It's what John suggested or not having a strongly typed view and adding them to the ViewData:

ViewData["Newest"] = Newest;
ViewData["Popular"] = Popular

Another option would be Strongly Typed Partial views.

jeef3
+1  A: 

You should make a model that includes both lists specifically for the view.

Typically in the little MVC I have done, I have made a model for each view even if they just passed along identically data that was served up for by data or business layer just to keep the separation between the two parts very strict. This setup is a little more work and not needed in many simple cases but it does keep things cleaner in my opinion.

Kelsey
+4  A: 

There are two general philosophies to this. The first is to take the approach John Sheehan stanted. You create a custom view model with both lists and pass that to your strongly typed view.

The second is to consider the lists as "ancillary" data and put them in ViewData like jeef3 stated. But, when you render the lists, you use a strongly typed partial.

ViewData["Newest"] = Newest;
ViewData["Popular"] = Popular

By that I mean in your main view, you'd call RenderPartial(...) but pass in the view data key you used.

<% Html.RenderPartial("Newest", ViewData["Newest"]); %>

And your partial would look like:

<%@ ViewUserControl Inherits="System.Web.Mvc.ViewUserControl<List<Item>>" %>
...

This gives you strongly typed access to that view data from within your partial.

Haacked