0

Data Tables in my application have lots of columns. Different users want different set of columns and in a particular order. The way I'm doing is, I have unique ID associated with each column for a table and I'm storing them in user preference. For example:

columnsToDisplay = "1,4,23,12,2,5,6,7,8,13,15"

In my view I'm using if else if to iterate though my table model (I'm using ASP.NET MVC) to render the table. I feel this is not the right way to do. Imagine a table with 50 columns and doing if else if 50 times! What's the ideal approach for this problem without using jQuery or any client side script plugin?

EDIT: Here is what I'm doing now. I'm comparing each column with use preference.

foreach(var col in model)
{ if(col.name == id) {
<td>{{id}}</td>}else if(col.name == customerName) {
<td>{{name}}</td>}else if(col.name == balance) {
<td>{{balance}}</td>}else if(col.name == createdOn) {
<td>{{createdOn}}</td>} 
}
.....

and so on...

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Amitava
  • 5,013
  • 9
  • 37
  • 50
  • This is an old question but here is another solution: http://stackoverflow.com/a/28611217/215752 – Hogan Feb 19 '15 at 16:44

1 Answers1

0

If these tables are readonly (you don't need to be able to post them back to the server), you could probably get away with throwing your model data into an array of IDictionary objects. Then you could use the values of your columnsToDisplay (as an array of ints) to get the relevant column when creating the view.

Something like this, assuming your model is called model:

model.ColumnArray = { 2, 4, 6, 1, 0 };

Then, assuming the model has a property called Rows that has your IDictionary objects:

@foreach(var model in Model.Rows)
{
    <tr>
    foreach(var column in Model.ColumnArray)
    {
        <td>@model[column]</td>
    }
    </tr>
}
Tieson T.
  • 20,774
  • 6
  • 77
  • 92