2016-01-06 85 views
3

我想使动态视图显示实体属性的列表。在MVC中以列表形式创建动态视图

我创建这些模型

public class PersonModel 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

} 

    public class EmployeeModel : PersonModel 
    { 
     public string CompanyName { get; set; } 

     } 

public class StudentModel : PersonModel 
    { 
     public string SchoolName { get; set; } 

    } 

我想一个观点,即显示列表视图动态生成 的例子列和数据出现在列表中。

例如,当开放的员工,我会表现出以下几点:

enter image description here

开放时的学生,我将显示如下:

enter image description here

什么使我的观点动力,并包含最简单的方法我想要的列和数据?

+0

您可以创建两个由不同型号键入的部分视图,然后在视图中使用该视图。可能会让您的操作方法切换到每个模型并返回到视图。 – Rahul

+0

使用反射? –

+0

相当困难。希望我的回答能够满足你的需求。 –

回答

1

我希望这样做的意义与我的想法一样!

由于List<PersonModel>,List<EmployeeModel>List<StudentModel>实际上被认为是完全不同的,您需要一种方法来解决这个问题。我使用通用的容器类:

public interface IGenericContainer 
{ 
    dynamic Data { get; } 
} 

public class GenericContainer<T> : IGenericContainer 
{ 
    T _Data { get; set; } 
    public GenericContainer(T data) 
    { 
     _Data = data; 
    } 
    dynamic IGenericContainer.Data 
    { 
     get { return _Data; } 
    } 
} 

public class GenericContainer 
{ 
    public static GenericContainer<T> Create<T>(T data) 
    { 
     return new GenericContainer<T>(data); 
    } 
} 

然后,您需要一个使用此类的通用视图。将这个共享/ DisplayTemplates/GenericGrid.cshtml

@using System.Reflection; 
@using System.Text; 
@{ 
    Layout = null; 
} 
@model IGenericContainer 
@{ 
    IEnumerable<PropertyInfo> properties = null; 
    if (Model.Data.Count > 0) 
    { 
     properties = Model.Data[0].GetType().GetProperties(); 
    } 
} 
<div> 
@if (properties != null) 
{ 
    <table> 
     <thead> 
      <tr> 
       @foreach (var prop in properties) 
       { 
        <td>@prop.Name</td> 
       } 
      </tr> 
     </thead> 
     <tbody> 
      @for (int i = 0; i < Model.Data.Count; i++) 
      { 
       <tr> 
       @foreach (var prop in properties) 
       { 
        <td>@prop.GetValue(Model.Data[i])</td> 
       } 
       </tr> 
      } 
     </tbody> 
    </table> 
} 
</div> 

要使用这个,你需要把它添加到您的视图:

@Html.DisplayFor(m => GenericContainer.Create(Model.PersonList), "GenericGrid") 

而且PersonList是在你的List<PersonModel>类型或模型的属性您的任何模型的列表。

+0

真棒,我喜欢它,有没有办法加载父类属性,然后驱动类,例如上面的员工我需要名字,姓氏,然后公司名称? – Jala

+0

尝试将'GetProperties()'更改为'GetProperties()。OrderBy(x => x。MetadataToken)' –

+0

如果这不起作用,那么这个问题有一个答案,看起来可能会做这个工作:http://stackoverflow.com/questions/358835/getproperties-to-return-all-properties-for-an -interface继承层次结构 –

1

我真的不知道如果我正确地理解你的要求,但如果你想显示你的模型的每个属性动态的列标题,那么你可以尝试以下方法:

在您看来,你可以调用的类型的GetProperties方法和递归添加一列每个属性:

@model PersonModel 
@if (Model != null) 
{ 
    <table style="width:100%"> 
     <tr> 
      @foreach (string property in Model.GetType().GetProperties().Select(x => x.Name).ToList()) 
      { 
      <td>@property</td> 
      } 
     </tr> 
    </table> 
} 

您填充行之前,你可以用这个例子来填充表格的标题列。要填充行,您需要一个PersonModel的列表,并对此进行一次foreach,类似于我向列标题显示的内容。

希望有所帮助。

+0

谢谢,我需要任何模型的一般视图。所以现在看不到这种类型的模型 – Jala