Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 如何在视图中处理具有继承性的实体模型?_Asp.net Mvc_Entity Framework - Fatal编程技术网

Asp.net mvc 如何在视图中处理具有继承性的实体模型?

Asp.net mvc 如何在视图中处理具有继承性的实体模型?,asp.net-mvc,entity-framework,Asp.net Mvc,Entity Framework,假设我有一个实体模型,由实体车和从汽车继承的两个实体跑车和卡车组成 在我的网站上,我想展示一系列汽车,混合了跑车和卡车,但也展示了各自的独特功能 在我的控制器中,我从模型中检索所有汽车并将它们发送到视图 如何在我的视图中构建逻辑来检查汽车是跑车还是卡车?您可以使用显示模板。让我们举个例子 型号: public class Car { public string CommonProperty { get; set; } } public class SportCar : Car {

假设我有一个实体模型,由实体车和从汽车继承的两个实体跑车和卡车组成

在我的网站上,我想展示一系列汽车,混合了跑车和卡车,但也展示了各自的独特功能

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


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

您可以使用显示模板。让我们举个例子

型号:

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" },
        };
    }
}
View~/Views/Home/Index.cshtml:

卡车的显示模板~/Views/Home/DisplayTemplates/truck.cshtml:


谢谢你的回答!我要试试看!
@model Car[]

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