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

问题描述 投票:2回答:1

来自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缺少一些东西,但是我尝试了许多没有成功的事情。

如果你能告诉我我缺少什么,那将是非常有帮助的。

谢谢

c# asp.net-mvc razor asp.net-mvc-viewmodel generic-type-argument
1个回答
3
投票

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

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

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

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

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

@model GenericModelType<IEntity>
© www.soinside.com 2019 - 2024. All rights reserved.