【问题标题】:How to handle an entity model with inheritance in a view?如何在视图中处理具有继承的实体模型?
【发布时间】:2012-05-07 03:43:06
【问题描述】:

假设我有一个由实体 Car 和 2 个从 Car 继承的实体(SportsCar、Truck)组成的实体模型。

我想在我的网站上显示汽车列表,混合了跑车和卡车,同时也显示每种汽车的独特功能。

在我的控制器中,我从模型中检索所有汽车并将它们发送到视图。

如何在我的视图中构建逻辑来检查汽车是跑车还是卡车?

【问题讨论】:

    标签: asp.net-mvc entity-framework


    【解决方案1】:

    您可以使用显示模板。举个例子吧。

    型号:

    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; }
    }
    

    控制器:

    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" },
            };
        }
    }
    

    查看(~/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>
    }
    

    跑车的显示模板 (~/Views/Home/DisplayTemplates/SportCar.cshtml):

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

    卡车的显示模板 (~/Views/Home/DisplayTemplates/Truck.cshtml):

    @model Truck
    @Html.DisplayFor(x => x.TruckSpecificProperty)
    

    【讨论】:

    • 感谢您的回答!我试试看!
    猜你喜欢
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多