I have two views that render a table on each. Most of the tables are shared between both views so I want to be able to reuse the view code for them both.
Table 1
Column A | Column B
1 | 2
4 | 8
Table 2
Column A | Column B | Column C
1 | 2 | 7
4 | 8 | 2
Obviously, my actual tables are a lot more complicated than the example above, which only serves to compound the problem. Because of how tables are written in HTML, there seems to me no good way to cut out the stuff I want to reuse while still having the ability to add to it.
Using tables, are there any methods I can employ to reuse the code or will I have to move away from using tables?
Why not just create a view that specializes in building a table given a specific model that includes all the column and row information? That way, you can use the view anywhere you want, and the model you give it will determine how many columns and rows there are.
Edit
I don’t think you’re quite understanding my point, so I’ll use some code. Right now you probably have a model that looks something like this:
And your view probably looks something like this:
Well, as you have noticed, this doesn’t lend itself well to simply columns from the table. One solution would be to set some options on the module to determine which columns get included, and then throw a bunch of
if/thenstatements into your view. But I think a better solution would be to make a new Model class that looks more like this:Then your model looks more like this:
As you can see, there is nothing in this view code that ties itself explicitly to your original data type, so it can be reused for any table you want to create throughout your entire application. Your controller becomes responsible for creating a TableModel object from the data that you want to represent. If a particular column gets included in that model, it will be displayed. If not, it won’t.
Obviously, like your example, this is extremely simplified, but it should give you the general idea. The
DataTableclass, which is already part of .NET, might already have everything you need, so you won’t even have to create your ownTableModelclass. It’s already got some nice functionality around adding and removing columns, rows, etc.