码迷,mamicode.com
首页 > Web开发 > 详细

生成HTML表格的后台模板代码

时间:2016-08-03 23:57:20      阅读:415      评论:0      收藏:0      [点我收藏+]

标签:

有时候,我们需要在后台拼接生成前端的html表格,一般的做法就是各种string、StringBuilder的拼接(例子省略...),这样的话如果表头不同就没法做到代码的重用,增加代码的冗余,下面我分享我的做法,以达到各位大牛抛砖引玉的效果。

首先新建一个公共配置静态类CommonConfiguration:

 public static class CommonConfiguration
    {
        public static string Width { get { return "Width"; } }

        public static string HeaderName { get { return "HeaderName"; } }

        /// <summary>
        /// 定义表格单元
        /// </summary>
        public static string TableTdBody { get { return "<td>{0}</td>"; } }
    }

接着定义一个公共帮助类:

public class CommonHelper
    {
        private const string FormatString = "<table style=\"{0}\" class=\"{1}\">";
        private const string FormatTableHeader = "<th style=\"width:{0}px;\">{1}</th>"; // 定义表头字符串

        /// <summary>
        /// 生成前端table模板
        /// </summary>
        /// <typeparam name="T">表头实体</typeparam>
        /// <param name="style">样式</param>
        /// <param name="className">类名</param>
        /// <param name="bodyString">表身</param>
        /// <param name="tableHeader">表头实体数据</param>
        /// <returns>Table模板</returns>
        public static string HtmlResult<T>(string style, string className, string bodyString,
            List<T> tableHeader) where T : class
        {
            var builder = new StringBuilder();

            builder.AppendFormat(FormatString, style, className);

            builder.Append("<tr>");
            foreach (var item in tableHeader)
            {
                builder.AppendFormat(FormatTableHeader, GetPropertyValue(item, CommonConfiguration.Width),
                    GetPropertyValue(item, CommonConfiguration.HeaderName));
            }
            builder.Append("</tr>");
            builder.Append(bodyString);

            builder.Append("</table>");

            return builder.ToString();
        }

        /// <summary>
        /// 根据属性名取得值
        /// </summary>
        /// <param name="entity">泛型实体</param>
        /// <param name="propertyName">属性名</param>
        /// <returns>对应属性值</returns>
        public static string GetPropertyValue<T>(T entity, string propertyName) where T : class
        {
            var type = entity.GetType();
            var propertyInfo = type.GetProperty(propertyName);
            var value = (string)propertyInfo.GetValue(entity);
            return value;
        }
    }

    public class TableHeader
    {
        /// <summary>
        /// 表头宽度
        /// </summary>
        public string Width { get; set; }
        /// <summary>
        /// 表头名
        /// </summary>
        public string HeaderName { get; set; }
    }

类TableHeader可定义自己喜欢的位置,我定义在这里是为了方便,代码很清晰,相信很容易看懂。

最后新建一个控制器HomeController用于调用这些代码生成html表格:

public ActionResult Index()
        {
            string tableBody = CommonConfiguration.TableTdBody;
            StringBuilder sb = new StringBuilder();


            var tableList = new List<TableHeader>
            {
                new TableHeader { Width = "10", HeaderName = "Id" },
                new TableHeader { Width = "20", HeaderName = "CustomerGuid" },
                new TableHeader { Width = "30", HeaderName = "Username" },
                new TableHeader { Width = "40", HeaderName = "Email" },
                new TableHeader { Width = "50", HeaderName = "Password" },
                new TableHeader { Width = "60", HeaderName = "PasswordSalt" },
                new TableHeader { Width = "70", HeaderName = "Active" },
                new TableHeader { Width = "80", HeaderName = "Deleted" },
                new TableHeader { Width = "90", HeaderName = "LastIpAddress" },
                new TableHeader { Width = "100", HeaderName = "CreatedOn" },
            };

            var customers = _customerService.GetCustomers().ToArray();

            customers.ForEach(c =>
            {
                sb.AppendFormat("<tr class=\"{0}\">", c.Active ? "success" : "warning");
                sb.AppendFormat(tableBody, c.Id);
                sb.AppendFormat(tableBody, c.CustomerGuid);
                sb.AppendFormat(tableBody, c.Username);
                sb.AppendFormat(tableBody, c.Email);
                sb.AppendFormat(tableBody, c.Password);
                sb.AppendFormat(tableBody, c.PasswordSalt);
                sb.AppendFormat(tableBody, c.Active);
                sb.AppendFormat(tableBody, c.Deleted);
                sb.AppendFormat(tableBody, c.LastIpAddress);
                sb.AppendFormat(tableBody, c.CreatedOn.ToString("yyyy-MM-dd"));
                sb.Append("</tr>");
            });

            var htmlResult = CommonHelper.HtmlResult("border-color: solid 1px #008000", "table table-striped", sb.ToString(), tableList);

            ViewBag.Result = MvcHtmlString.Create(htmlResult);

            return View();
        }

视图页:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="container">
    @ViewBag.Result
</div>

最后查看生成的html格式效果:

技术分享

 

  <table style="border-color: solid 1px #008000" class="table table-striped">
   <tbody>
    <tr>
     <th style="width:10px;">Id</th>
     <th style="width:20px;">CustomerGuid</th>
     <th style="width:30px;">Username</th>
     <th style="width:40px;">Email</th>
     <th style="width:50px;">Password</th>
     <th style="width:60px;">PasswordSalt</th>
     <th style="width:70px;">Active</th>
     <th style="width:80px;">Deleted</th>
     <th style="width:90px;">LastIpAddress</th>
     <th style="width:100px;">CreatedOn</th>
    </tr>
    <tr class="success">
     <td>1</td>
     <td>bee62ba2-9d53-495f-80d4-af4fe6ddaa16</td>
     <td>Allen</td>
     <td>875755898@qq.com</td>
     <td>0D59DB9C0211A16786F5EFD6B5809B6984B2AF96</td>
     <td>TW0lAH4=</td>
     <td>True</td>
     <td>False</td>
     <td>127.0.0.1</td>
     <td>2016-06-18</td>
    </tr>
   </tbody>
  </table>

这里我用了bootstrap作为表格的样式,你们可自定义class。

 

--鱼头鱼尾

--QQ:875755898

生成HTML表格的后台模板代码

标签:

原文地址:http://www.cnblogs.com/YUTOUYUWEI/p/5734790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!