通用HtmlHelper,用于从任何类型的列表创建html表

时间:2012-11-16 11:30:17

标签: c# .net asp.net-mvc

我想创建一个HtmlHelper来创建一个html表。我希望帮助器能够获取任何类型的对象列表以及要显示为列的对象属性列表。像这样:

public static HtmlString Table(this HtmlHelper helper, List<T> data, List<string> headers)
    {
        //Tags
        TagBuilder table = new TagBuilder("table");
        TagBuilder tr = new TagBuilder("tr");
        TagBuilder td = new TagBuilder("td");
        TagBuilder th = new TagBuilder("th");

        //Inner html of table
        StringBuilder sb = new StringBuilder();

        //Add headers
        foreach (var s in headers)
        {
            th.InnerHtml = s;
            tr.InnerHtml += th.ToString();
        }
        sb.Append(tr.ToString());

        //Add data
        foreach (var d in data)
        {
            tr.InnerHtml = "";
            foreach (var h in headers)
            {
                td.InnerHtml = d.h.ToString();
                tr.InnerHtml += td.ToString();
            }
            sb.Append(tr.ToString());
        }

        table.InnerHtml = sb.ToString();
        return new HtmlString(table.ToString());
    }

这段代码当然行不通,但我想知道是否有可能做出类似的东西?我将如何做到这一点。

编辑:

我选择了以下解决方案,其想法是表格应该只包含标题列表中指定的元素,所以这就是我想出的:

public static HtmlString Table<T>(this HtmlHelper helper, List<T> data, List<string> headers)
{
    //Tags
    TagBuilder table = new TagBuilder("table");
    TagBuilder tr = new TagBuilder("tr");
    TagBuilder td = new TagBuilder("td");
    TagBuilder th = new TagBuilder("th");

    //Inner html of table
    StringBuilder sb = new StringBuilder();

    //Add headers
    foreach (var s in headers)
    {
        th.InnerHtml = s;
        tr.InnerHtml += th.ToString();
    }
    sb.Append(tr.ToString());

    //Add data
    foreach (var d in data)
    {
        tr.InnerHtml = "";
        foreach (var h in headers)
        {
            td.InnerHtml = d.GetType().GetProperty(h).GetValue(d, null).ToString();
            tr.InnerHtml += td.ToString();
        }
        sb.Append(tr.ToString());
    }

    table.InnerHtml = sb.ToString();
    return new HtmlString(table.ToString());
}

3 个答案:

答案 0 :(得分:8)

public HtmlTable BuildTable<T>(List<T> Data)
{
  HtmlTable ht = new HtmlTable();
  //Get the columns
  HtmlTableRow htColumnsRow = new HtmlTableRow();
  typeof(T).GetProperties().Select(prop =>
                                        {
                                          HtmlTableCell htCell = new HtmlTableCell();
                                          htCell.InnerText = prop.Name;
                                          return htCell;
                                        }).ToList().ForEach(cell => htColumnsRow.Cells.Add(cell));
  ht.Rows.Add(htColumnsRow);
  //Get the remaining rows
  Data.ForEach(delegate(T obj)
  {
    HtmlTableRow htRow = new HtmlTableRow();
    obj.GetType().GetProperties().ToList().ForEach(delegate(PropertyInfo prop)
    {
      HtmlTableCell htCell = new HtmlTableCell();
      htCell.InnerText = prop.GetValue(obj, null).ToString();
      htRow.Cells.Add(htCell);
    });
    ht.Rows.Add(htRow);
  });
  return ht;
}

试试吧。您需要致电BuildTable<YourType>(list)

答案 1 :(得分:3)

.NETStandard 2.0可以使用HtmlTableHelper

小提琴演示:

扩展名

ASP.NET Core MVC:
创建一个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", Gender = "M" } })
/*
Result:<table><thead><tr><th>Name</th><th>Age</th><th>Gender</th></tr></thead><tbody><tr><td>ITWeiHan</td><td>25</td><td>M</td></tr></tbody></table>
*/

ASP.NET MVC 5:
创建一个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);
    }
}

演示

ASP.NET MVC 5 jQuery DataTable演示:

using HtmlTableHelper;
//..
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var datas = new[] { new { Name = "ITWeiHan", Age = "25",Gender = "M" } };
        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>

答案 2 :(得分:0)

嗨,我更新了.NET核心版本的代码。 祝你好运

    public static IHtmlContent Table<T>(IList<T> data, IList<(string propertyName, string colName)> headers)
    {
        //Tags
        var table = new TagBuilder("table");
        var tr = new TagBuilder("tr");
        
        //Add headers
        foreach (var s in headers)
        {
            var th = new TagBuilder("th");
            th.InnerHtml.Append(s.colName);
            tr.InnerHtml.AppendHtml(th);
        }
        table.InnerHtml.AppendHtml(tr);

        //Add data
        foreach (var d in data)
        {
            tr = new TagBuilder("tr");
            foreach (var h in headers)
            {
                var td = new TagBuilder("td");
                td.InnerHtml.Append( d.GetType().GetProperty(h.propertyName).GetValue(d, null)?.ToString());
                tr.InnerHtml.AppendHtml(td);
            }
            
            table.InnerHtml.AppendHtml(tr);
        }

        return table;
    }