ASP.NET MVC Framework hands the complete control of the rendered HTML to the developer. Sometimes this control on rendered HTML can become a headache when the developer has to write repetitive view code. In this article we will demonstrate how to write an HTML helper for table which will eliminate the necessity to implement loop to create HTML tables.

Creating the Customer Entity Class:

We will be using a simple Customer class throughout this article. The implementation of the class is shown below:



Creating HTML Table Manually:

In this section we will be manually typing the HTML code to create the table structure. Before creating the table we need to supply the view with a list of customers. This is accomplished by populating the ViewData. The controller action "DemoGrid" is responsible for populating a dummy list of customers into the ViewData["Customers"] object as shown below:



The next piece of code creates the table using HTML elements. Take a look at the following implementation:



The result is shown below:



Although it is not a lot of code to create HTML table but it quickly becomes hard work if multiple tables are needed. It also becomes hard to maintain the code since if you need to add a particular feature to the HTML table you will have to go through all the tables and edit them manually. Let's see how we can move the HTML table implementation into the HTML helper class.

Creating HTML Helper:

If you are not familiar on how to create HTML helpers then we recommend that you check out the following resources.

1) Introduction to HTML Helpers
2) Creating ASP.NET MVC Helpers
3) Video: Introduction to HTML Helpers
4) Video: Creating ASP.NET MVC Helpers

There are many different ways of creating HTML elements using HTML helpers and most of them are discussed in the above mentioned resources. In this article we are going to use the HtmlTable class to create the HTML table.

The HTML helper is called Grid and it takes three arguments as shown below:



The description of the arguments is given below:

name: The name of the table   
list: The collection of elements that will make the Grid
columnNames: The column names used as column headers and used to extract the fields out of the entity

The CreateRowsWithList method returns all the created rows as HtmlTableRow[] array. The CreateHtmlTableCell method creates a HtmlTableCell instance and assigns the inner HTML property to the cell.



There are several other private methods used in the Grid HTML helper. The current implementation simply displays the collection as HTML table. You can add further features to the code to perform various tasks.   

Conclusion:

In this article we learned how to create a simple HTML helper to emit out HTML table. The Grid implemented in this article is too simple to be used in any application but you can extend the Grid by adding more features.

[Download Sample]