Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 870
Martin Avatar asked Aug 14 '09 02:08

Martin


People also ask

Can we use 2 models in a view?

You can use multiple models in a single view by creating a common model for all the models that are to be used in a single view. To achieve this, refer to the following steps. First, create a new model (common for all models) and refer all other models that are to be used in the same view.

What is strongly typed view in MVC with example?

The view which binds to a specific type of ViewModel is called as Strongly Typed View. By specifying the model, the Visual studio provides the intellisense and compile time checking of type. We learnt how to pass data from Controller to View in this tutorial. This is usually done using the ViewBag or ViewData.

Can a controller have multiple views?

Controller is the boss, so a Controller decides which View to be rendered and Views does not / cannot care which Controller requested the View. You can / will absolutely have multiple Views from a Controller.


2 Answers

"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; }
}
like image 72
John Sheehan Avatar answered Sep 23 '22 05:09

John Sheehan


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.

like image 41
Haacked Avatar answered Sep 22 '22 05:09

Haacked