2014-10-06 83 views
0

我實現了一個通用的WebGrid類,它根據指定的(行)模型呈現其html標記。ASP.NET:通用列表中的剃刀

public class WebGrid<TRow> where TRow : WebGridRow{ 

    public WebGrid(string tableId, IList<TRow> rows){ 

     // Generate columsn from Model (TRow) by reflection 
     ... 
    } 

    public MvcHtmlString GetHtml(HtmlHelper helper) { 
     return new MvcHtmlString(...); 
    } 

} 

public abstract class WebGridRow { 
    public virtual string GetRowId() { 
     return "row_" + Guid.NewGuid(); 
    } 
} 

可以在模型類中定義佈局,...以及屬性。 例如:

public class MyRowModel : WebGridRow { 

    [CanFilter(false)] 
    [CssClass("foo")] 
    public string Name{get;set;} 

    [CanFilter(true)] 
    [CssClass("bar")] 
    public int SomeOtherProperty{get;set;} 

} 

現在我想創建一個通用視圖,顯示WebGridRow的亞類中的WebGrid的任何名單。問題是Razor不支持通用視圖模型。

有沒有人有一個想法我怎麼能解決這個問題?

+0

你所說的「剃刀不支持泛型觀點的意思是楷模」 ?您始終可以將視圖的模型定義爲WebGrid 。 – Whoami 2014-10-06 12:45:08

+0

這是正確的。但是我無法將模型定義爲WebGrid ! – Tobias 2014-10-06 12:48:59

+0

什麼是錯誤?因爲我在視圖中使用了很多泛型。您沒有收到ICollection 型號的視圖嗎?你確定你不錯過你的觀點(包含WebGrid 類)嗎? – Whoami 2014-10-06 12:51:57

回答

1

這會幫助你

模式

public interface IWebGrid 
{ 
    MvcHtmlString GetHtml(HtmlHelper helper); 
} 

public class WebGrid<TRow> : IWebGrid where TRow : WebGridRow 
{ 
    private ICollection<TRow> Rows {get;set;} 

    public WebGrid(string tableId, IList<TRow> rows) 
    { 
     // Generate columns from Model (TRow) by reflection and add them to the rows property 
    } 

    public MvcHtmlString GetHtml(HtmlHelper helper) 
    { 
     string returnString = "Generate opening tags for the table itself"; 
     foreach(TRow row in this.Rows) 
     { 
      // Generate html for every row 
      returnString += row.GetHtml(helper); 
     } 
     returnString += "Generate closing tags for the table itself"; 
     return MvcHtmlString.Create(returnString); 
    } 
} 

public abstract class WebGridRow 
{ 
    public virtual string GetRowId() 
    { 
     return "row_" + Guid.NewGuid(); 
    } 

    public abstract MvcHtmlString GetHtml(HtmlHelper helper); 
} 

public class MyRowModel : WebGridRow 
{ 
    [CanFilter(false)] 
    [CssClass("foo")] 
    public string Name{get;set;} 

    [CanFilter(true)] 
    [CssClass("bar")] 
    public int SomeOtherProperty{get;set;} 

    public override MvcHtmlString GetHtml(HtmlHelper helper) 
    { 
     // Generate string for the row itself 
    } 
} 

查看 (顯示模板與否)

@model IWebGrid 
@model.GetHtml(this.Html); 
+0

這看起來不錯。但這意味着網格是一個模型,這是明確的錯誤,因爲網格只是一個控制。或者我理解錯了什麼? – Tobias 2014-10-06 13:49:17

+0

好吧,沒有看到你想使用DataGrid控件。爲什麼你想要一個GetHtml()函數,然後如果網格自己繪製?你是不是把它作爲一個對象來自己繪製你自己的標籤? – Whoami 2014-10-06 14:07:21

+0

是的:接口是要走的路! – Tobias 2014-10-15 09:22:18