How to handle an entity model with inheritance in a view?

扶醉桌前 提交于 2020-01-25 07:41:07

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/10473419/how-to-handle-an-entity-model-with-inheritance-in-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!