Tobias
Tobias

Reputation: 2985

ASP.NET: Generic List in Razor

I implemented a generic WebGrid-Class that renders its html-markup according to the specified (row)model.

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();
    }
}

It is possible to define layout, ... with attributes in a model class. For example:

public class MyRowModel : WebGridRow {

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

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

}

Now I want to create a generic view, that shows any List of subclasses of WebGridRow as WebGrid. Problem is that Razor does not support generic view models.

Does anyone have an idea how could I solve this?

Upvotes: 0

Views: 1104

Answers (1)

Whoami
Whoami

Reputation: 334

This should help you

Models

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
    }
}

View (display template or not)

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

Upvotes: 1

Related Questions