具有可变模型类型的局部视图

Partial View with variable model type

Travis 更新的回答:

public interface IEntity
{
    int Id{get;set;}
    string Name{get;set;}
}
public class Vehicule:IEntity
{
    public int Id{get;set;}
    public string Name{ get; set; }
}
public class Sector:IEntity
{
    public string Id{ get; set; }
    public string Name{ get; set; }
}

主视图的模型:

public class MainViewModel
{
    public Vehicule Vehicule{ get; set; }
    public Sector Sector{ get; set; }
}

现在我想为每个实体实现一个表单(这将是一个模态表单,但这不是重点)。 它会更复杂,但例如它只是:

@Html.TextBoxFor(m=>m.Name)
//etc...

我正在尝试使用泛型类型实现接口,但我真的不明白该怎么做,尤其是泛型类型。

现在我的部分视图中有 @model GenericViewModel<IEntity>,我的视图中有 MainViewModel

如何使用泛型将模型传递给分部视图?

@Html.RenderPartial("_PartialView",????)

我认为 MainViewModel 中缺少一些东西,但我尝试了很多东西都没有成功。

如果你能告诉我我遗漏了什么,那将非常有帮助。

谢谢

使用接口公开不同类型的属性或行为。

public interface IEntity
{
    string PropertyA;
    string PropertyB;
    string PropertyC;
}

然后让每个实体继承这个接口

public class Entity1 : IEntity { ... }
public class Entity2 : IEntity { ... }
public class Entity3 : IEntity { ... }

现在在您的视图中,您可以将界面属性公开给实体

@model GenericModelType<IEntity>