【问题标题】:Partial View with variable model type具有可变模型类型的局部视图
【发布时间】:2018-09-21 19:06:33
【问题描述】:

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】:

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

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

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

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

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

    @model GenericModelType<IEntity>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 2014-06-27
      • 1970-01-01
      • 2014-03-15
      • 2011-10-11
      • 1970-01-01
      • 2012-06-09
      相关资源
      最近更新 更多