Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC3 View inheritance

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?

like image 397
Nathan Koop Avatar asked Mar 10 '26 20:03

Nathan Koop


1 Answers

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:

  1. ASP.NET MVC sees that the model is an IEnumerable<Vehicle>
  2. ASP.NET MVC starts enumerating over this collection
  3. For each element of the collection ASP.NET MVC looks at its concrete runtime type.
  4. ASP.NET MVC looks for a corresponding display template for this type defined in the ~/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.

like image 168
Darin Dimitrov Avatar answered Mar 13 '26 17:03

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!