views:

178

answers:

2

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?

+2  A: 

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!

Simon Steele
+2  A: 

You can think about using reflection:

class UserViewModel
{
    [DisplayName("User name")]
    public string UserName { get; set; }

    [DisplayName("E-mail address")]
    public string Email { get; set; }

    [DisplayName("Age")]
    public int Age { get; set; }
}

Then you can easily access properties through reflection and save selected property list in user settings. You can access display name through reflection too (it is not here):

var type = typeof(UserViewModel);
var properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    Console.WriteLine(property.Name);
}

You don't have to create additional types and description. Attributes give you display name and reflection gives you list. That is how ASP.NET MVC works. Similar mechanism is used when you want to use Html.EditorFor(Model) and many other in this framework.

LukLed