2016-01-06 51 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