I am trying to build a HTML table using WebMatrix (ASP.NET Web Pages) but am having trouble due to the way the HTML tags are opened and closed.
What I am trying to achieve is to create a table from a recordset, with three columns, and then fill in any empty columns.
This is some test code I am using to work out how to do this using WebMatrix.
<table>
@{
int row = 0;
int col = 0;
for (int i = 0; i < 20; i++) //20 cells for test purposes
{
col++;
if (col == 4)
{
col = 1;
}
if (col == 1)
{
row++;
if (row != 1)
{
</tr>
}
<tr>
}
<td>@i</td>
}
for (int i = col; i <=3; i++)
{
<td>empty</td>
}
</tr>
}
</table>
Any suggestions for how best to accomplish this.
How about grouping your dataset before printing it? It ASP.NET MVC terms this is called view model. Unfortunately in WebMatrix you don't have a controller which could do the job of preparing this view model but you could do it in the codebehind or whatever this section of the Razor page is called:
and if you had a dataset of complex objects and not just integers, here's how the grouping could be done:
and then:
It kind of makes the code much more readable. As you can see the usage of a view model avoids you from writing ugly spaghetti code in the views.
Every-time you have some unmatched tags and you need to do integer and modulo divisions and stuff in a view you are probably doing it wrong as you didn't pick up the correct view model.
Updated code sample based on the revised requirement:
Hopefully, I've understood what you are after this time.
If you want to build the table from a recordset, why not do that? Here's an example using the Northwind database:Or you could use the WebGrid to do this for you.