Click here to Skip to main content
13,863,412 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

3.3K views
11 bookmarked
Posted 3 Feb 2019
Licenced CPOL

HtmlTableHelper, Mini C# IEnumerable Object to HTML Table String Library

, 3 Feb 2019
Rate this:
Please Sign up or sign in to vote.
Mini C# IEnumerable object to HTML Table String Library

Introduction

The reason for making HtmlTableHelper is that I often need to do "convert collection objects to HTML-table string". This is required not only for ASP.NET(or MVC), but also for generating static .html files.

I find there are many good packages on the Internet like:

  • JsonToTable
    • Advantage: It focuses on convert collection of data to Json string by Json.NET.
    • Premise: It needs to depend on JavaScript environment, with Json.NET.
  • MVCtable
    • Advantage: It can be converted to HTML Table string in the Server directly
    • Premise: It needs to depend on ASP.NET MVC5 and ASP.NET Core MVC.

So I write HtmlTableHelper for:

  • "Mini" DLL file size is only 18KB
  • It does not depend on any third-party library
  • .NET Standard 2.0 supports .NET Framework and .NET Core
  • Easy to use, just need to understand `ToHtmlTable()` method
  • Supports Anonymous Types, Dapper Dynamic Query, List/Array/Set/Enumrable, DataTable, Dictionary

Get Started

List/Array/Set/Enumerable non Key/Value Type Example

using HtmlTableHelper;
..
var sourceData = new[] { new { Name = "ITWeiHan", Age = "25",Country = "Taiwan" } };
var tablehtml = sourceData.ToHtmlTable();
/*
Result:
<table><thead><tr><th>Name</th><th>Age</th><th>Country</th></tr></thead>
<tbody><tr><td>ITWeiHan</td><td>25</td><td>Taiwan</td></tr></tbody></table>
*/

Dapper Example

using (var cn = "Your Connection")
{
	var sourceData = cn.Query(@"select 'ITWeiHan' Name,25 Age,'Taiwan' Country");
	var tablehtml = sourceData.ToHtmlTable();
}

Dictionary Example

var sourceData = new[] {new Dictionary<string, object> ()
{{"Name" , "ITWeiHan" },{"Age",25},{"Country","Taiwan"}}};
var tablehtml = sourceData.ToHtmlTable();

Custom Table/TR/TD Attributes (Dynamic Type)

var data = /*List/Array/Set/Enumrable..*/;
var html = data.ToHtmlTable( tableAttributes: 
    new { @class = "SomeClass"} //this is dynamic type, support all attribute 
    ,trAttributes: new { ID = "SomeID" },tdAttributes: new { width = "120 px" }
);
/*
Result:
<table class="SomeClass">
	<thead>
		<tr ID="SomeID">
			<th>..</th>
		</tr>
	</thead>
	<tbody>
		<tr ID="SomeID">
			<td width="120 px">..</td>
		</tr>
	</tbody>
</table>
*/

Attribute Annotation

1. Display

public class ModelClassWithDisplayAttr
{
    [TableColumn(DisplayName = "Column1")] //MyProperty1 property will render 
                                           //thead-td's innertext : "Column1"
    public string MyProperty1 { get; set; }
    [TableColumn(DisplayName = "Column2")] //MyProperty2 property will render 
                                           //thead-td's innertext : "Column2"
    public string MyProperty2 { get; set; }
}

2. Skip

public class ModelClassWithSkipAttr
{
    [TableColumn( Skip = true)]
    public string MyProperty1 { get; set; } //MyProperty1 will not render html
    public string MyProperty2 { get; set; }
}

HTMLTableSetting

Configurable InnerHtml Encoding (Recommended not to do so without a specific reason, because XSS Attack):

var sourceData = new[] { new { Name = "<b>ITWeiHan</b>" } };

//Default Encoding
var encodinghtml = sourceData.ToHtmlTable();
//Result: <table>..&lt;b&gt;ITWeiHan&lt;/b&gt;..</table>

var htmltablesetting = new HTMLTableSetting()
{
    IsHtmlEncodeMode = false
};
var notEncodinghtml = sourceData.ToHtmlTable(HTMLTableSetting: htmltablesetting);
//Result: <table>..<b>ITWeiHan</b>..</table>

Extension

ASP.NET Core MVC

It needs to create an IHtmlHelperExtension.cs:

using System.Collections.Generic;
using HtmlTableHelper;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Html;

public static class IHtmlHelperExtension
{
    public static HtmlString ToHtmlTable<T>(this IHtmlHelper htmlHelper, IEnumerable<T> enums
        , object tableAttributes = null, object trAttributes = null, object tdAttributes = null
        , HtmlTableSetting HTMLTableSetting = null)
    {
        var html = enums.ToHtmlTable(tableAttributes, trAttributes, tdAttributes, HTMLTableSetting);
        return new HtmlString(html);
    }

    public static HtmlString ToHtmlTable<T>(this IHtmlHelper htmlHelper, System.Data.DataTable datatable
        , object tableAttributes = null, object trAttributes = null, object tdAttributes = null
        , HtmlTableSetting HTMLTableSetting = null)
    {
        var html = datatable.ToHtmlTable(tableAttributes, trAttributes, tdAttributes, HTMLTableSetting);
        return new HtmlString(html);
    }
}

razor.cshtml

@Html.ToHtmlTable(new[] { new { Name = "ITWeiHan", Age = "25", Country = "Taiwan" } })
/*
Result:<table><thead><tr><th>Name</th><th>Age</th><th>Country</th></tr></thead>
<tbody><tr><td>ITWeiHan</td><td>25</td><td>Taiwan</td></tr></tbody></table>
*/

ASP.NET MVC 5

It needs to create an HtmlHelperExtension.cs:

using System.Collections.Generic;
using HtmlTableHelper;
using System.Web;
using System.Web.Mvc;

public static class HtmlHelperExtension
{
    public static HtmlString ToHtmlTable<T>(this HtmlHelper htmlHelper, IEnumerable<T> enums
        , object tableAttributes = null, object trAttributes = null, object tdAttributes = null
        , HtmlTableSetting HTMLTableSetting = null)
    {
        var html = enums.ToHtmlTable(tableAttributes, trAttributes, tdAttributes, HTMLTableSetting);
        return new HtmlString(html);
    }

    public static HtmlString ToHtmlTable<T>(this HtmlHelper htmlHelper, System.Data.DataTable datatable
        , object tableAttributes = null, object trAttributes = null, object tdAttributes = null
        , HtmlTableSetting HTMLTableSetting = null)
    {
        var html = datatable.ToHtmlTable(tableAttributes, trAttributes, tdAttributes, HTMLTableSetting);
        return new HtmlString(html);
    }
}

Demo

ASP.NET MVC 5 JQuery DataTable Demo

Demo Link: ASP.NET MVC 5 Demo 2019-01-17.10.34.47-image.png

using HtmlTableHelper;
//..
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var datas = new[] { new { Name = "ITWeiHan", Age = "25",Country = "Taiwan" } };
        ViewBag.Table = datas.ToHtmlTable();
        return View();
    }
}
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AspNetMvcDemo</title>
    <link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
</head>
<body>
    <div>
        @Html.Raw(ViewBag.Table)
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            $('Table').DataTable();
        });
    </script>
</body>
</html>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ITWeiHan
Taiwan Taiwan
No Biography provided

You may also be interested in...

Pro

Comments and Discussions

 
Generalthanks Pin
Member 141421636-Feb-19 8:25
memberMember 141421636-Feb-19 8:25 
GeneralMy vote of 5 Pin
BillWoodruff5-Feb-19 17:28
mveBillWoodruff5-Feb-19 17:28 
GeneralRe: My vote of 5 Pin
ITWeiHan5-Feb-19 19:30
memberITWeiHan5-Feb-19 19:30 
QuestionI did something like this where I wanted to export to CSV Pin
Sacha Barber5-Feb-19 5:06
mvaSacha Barber5-Feb-19 5:06 
AnswerRe: I did something like this where I wanted to export to CSV Pin
ITWeiHan5-Feb-19 19:30
memberITWeiHan5-Feb-19 19:30 
GeneralRe: I did something like this where I wanted to export to CSV Pin
Sacha Barber5-Feb-19 20:33
mvaSacha Barber5-Feb-19 20:33 
GeneralRe: I did something like this where I wanted to export to CSV Pin
ITWeiHan5-Feb-19 22:32
memberITWeiHan5-Feb-19 22:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 4 Feb 2019
Article Copyright 2019 by ITWeiHan
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid