Asp.Net MVC - Strongly Typed View with Two Lists of Same Type
Asked Answered
T

4

5

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.

Tampon answered 14/8, 2009 at 2:9 Comment(0)
E
10

"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; }
}
Emptyhanded answered 14/8, 2009 at 2:12 Comment(0)
B
4

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.

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.

Begorra answered 14/8, 2009 at 16:31 Comment(0)
C
3

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.

Califate answered 14/8, 2009 at 2:18 Comment(0)
G
1

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.

Gourmand answered 14/8, 2009 at 2:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.