Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding columns to a table in an ASP.NET MVC view

I am returning an IList to my model of data about users. I want my end users to be able to select which columns they want to see.

I know I can do this with a huge "if statement" however, I know there must be a better way.

I have created an Enum with the column names. I feel if I could take the IListItem.EnumName I would be set. However, I'm not too sure on how to do this.

Suggestions?

like image 760
Sara Chipps Avatar asked Apr 20 '10 20:04

Sara Chipps


1 Answers

I handled this by creating an IColumn interface and then a bunch of column classes that could correctly display different facets of my model. The view then renders each column with a simple for loop. For example:

public interface IColumn
{
    string Title { get; }
    string Render(MyModelObject obj);
}

public class NameColumn : IColumn
{
    public string Title { get { return "Name"; } }

    public string Render(MyModelObject obj)
    {
        return obj.Name;
    }
}

In your view you then do something like this:

<tr>
<% foreach (var column in Model.UserColumns) { %>
<th><%= column.Title %></th>
<% } %>
</tr>

<% foreach (var item in Model.Items) { %>
<tr>
    <% foreach (var column in Model.UserColumns) { %>
    <td><%: column.Render(item) %></td>
    <% } %>
</tr>
<% } %>

This has been working well for me!

like image 143
Simon Steele Avatar answered Oct 29 '22 02:10

Simon Steele