2014-10-06 85 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