Reputation: 25197
I've got a list of for example Vehicle's that I want to render in a single page, but have different view characteristics for each vehicle type.
Vehicle
- VehicleId
- VehicleTypeId (Car/Boat/Truck/etc...)
- Description
- ...
I'd like to on my main AllVehiclesPage
@foreach(var vehicle in Model) //where Model is a List<Vehicle> from AllVehicles
{
//Render proper View
//CarView(vehicle)
//BoatView(vehicle)
//TruckView(vehicle)
}
In each view it will render differently depending on the vehicle, IE Wheel rim size applies to cars/trucks not to boats etc...
I've read a number of the other questions on Stackoverflow about view inheritance, but they don't seem to apply.
Is this best to do with partial Views? Should I create Usercontrols?
Upvotes: 2
Views: 200
Reputation: 1038810
Use display templates. Replace your entire foreach loop with the following line of code:
@model IEnumerable<Vehicle>
...
@Html.DisplayForModel()
And now comes the interesting part. You define display templates for each type that you want to handle:
~/Views/Shared/DisplayTemplates/Car.cshtml
~/Views/Shared/DisplayTemplates/Boat.cshtml
~/Views/Shared/DisplayTemplates/Truck.cshtml
Each template will be strongly typed to the corresponding concrete type. So here's what will happen on the Html.DisplayForModel()
line:
IEnumerable<Vehicle>
~/Views/Shared/DisplayTemplates
folder and automatically renders it by passing this template the current element as model.You will notice something interesting in this pattern: I use the word ASP.NET MVC very much instead of the word the .NET developer. That's nifty because all that the developer has to do is follow the standard conventions and then ASP.NET MVC will do the job for him so that this developer doesn't need to write loops, doesn't need to write if conditions and doesn't need to reinvent wheels.
Upvotes: 9