0

Suppose I have an entity model consisting out of entity Car, and 2 entities (SportsCar, Truck) that inherit from Car.

On my site I want to display a list of Cars, mixing SportsCars and Trucks, but also displaying the unique features of each.

In my controller I retrieve all cars from my model and send them to the view.

How can I build logic in my view that checks wether a car is a SportsCar or a Truck?

Ron83
  • 92
  • 1
  • 6

1 Answers1

0

You could use display templates. Let's take an example.

Model:

public class Car
{
    public string CommonProperty { get; set; }
}

public class SportCar : Car
{
    public string CarSpecificProperty { get; set; }
}

public class Truck: Car
{
    public string TruckSpecificProperty { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new Car[]
        {
            new SportCar { CommonProperty = "sports car common", CarSpecificProperty = "car specific" },
            new Truck { CommonProperty = "truck common", TruckSpecificProperty = "truck specific" },
        };
    }
}

View (~/Views/Home/Index.cshtml):

@model Car[]

@for (int i = 0; i < Model.Length; i++)
{
    <div>
        @Html.DisplayFor(x => x[i].CommonProperty)
        @Html.DisplayFor(x => x[i])
    </div>
}

Display template for a sport car (~/Views/Home/DisplayTemplates/SportCar.cshtml):

@model SportCar
@Html.DisplayFor(x => x.CarSpecificProperty)

Display template for a truck (~/Views/Home/DisplayTemplates/Truck.cshtml):

@model Truck
@Html.DisplayFor(x => x.TruckSpecificProperty)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928