views:

1147

answers:

3

For Example: Let's say that I want to return a view that displays a list of cars and also show a section of dealers in your area. These are two disjointed pieces of data.

My view inherits a list of cars like the following:

public partial class CarLot : ViewPage<List<Cars>>
{

}

Now from the controller I can return the view like the following:

return View(Model.GetCars());

To render this, my markup would look something like the following:

<% foreach (Car myCar in ViewData.Model)
{some html here}
%>

This takes care of the list of cars, but my question is, how do I handle the list of dealers? Does the view support multiple inheritance or am I going to have to hit the model again form the markup? I know it can be done that way, but am not sure if it is the best practice.

+15  A: 

Create a data transfer object

public class CarLotViewModel
{
     public List<Car> Cars { get; set; }
     public List<Dealer> NearbyDealers { get; set; }
}

Set your view to use the view model:

public partial class CarLot : ViewPage<CarLotViewModel>
{    
}

Then in your controller:

CarLotViewModel model = new CarLotViewModel();
model.Cars = GetCars();
model.NearbyDealers = GetDealers();
return View(model);

Then enumerate each collection in your view:

<% foreach (Car car in ViewData.Model.Cars) { %>
....
<% foreach (Dealer dealer in ViewData.Model.NearbyDealers) { %>
John Sheehan
A: 

I am not a .Net or ASP developer but cant your view 'inherit' a model containing the list of cars and list of dealers instead of just the list of cars?

willcodejavaforfood
Yes. I was trying to avoid creating a new object just for the view, but that may be the best option.
Eric Brown
A: 

Set your view to use the view model:

public partial class CarLot : ViewPage { }

There is no code-behind in MVC 1.0. How do you set the view to use view model?

xraminx
It's a ASPX. Code-behind is allowed, although discouraged because it violates the ideals of separating Controller and View.
Justice
Well, I dont use the code behind. But in Preview and Beta, the ViewPage inheritance defaulted to the code behind page. Now, for a strongly typed View it occurs in the markup. In Release 1.0 it would look like this: Inherits="System.Web.Mvc.ViewPage<CarLotViewModel>" in the page markup.
Eric Brown