Asp.net后台创建HTML

为了使HTML界面中的内容能根据数据库中的内容动态显示用户需要的内容,或者根据权限不同要显示同而实现页面内容的动态创建

使用HtmlGenericControl创建HTML标签

引入命名空间: using System.Web.UI.HtmlControls;

更改其属性: hgg_div.Attributes.Add("style","200px; height:200px;");

内容设置: hgg_div.InnerText = "我是一个" + htmlTag;(htmlTag可以是div,br,span…)

或者InnerHtml来给div写一些html

使用Table newTable = new Table();创建表格控件

newTable.Width = 200;设置高

newTable.Height = 200; 设置宽

创建行: TableRow newTableRow = new TableRow();

newTableRow.Height = 20;

创建单元格: TableCell newTableCell = new TableCell();

newTableCell.Width = 100;

newTableCell.Text = "我是一个单元格";

添加到表格中: newTableRow.Controls.Add(newTableCell);

newTableRow.Controls.Add(newTableCell);

newTable.Controls.Add(newTableRow);

将创建的标签或者控件添加到页面中

Page.Controls.Add(newTable);//添加到表单外(control)

Page.Form.InnerHtml=str;//添加到表单内(html)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

    public partial class xuexi_aspnet_ChuangJianHtml : System.Web.UI.Page
    {
        #region 窗体加载

        protected void Page_Load(object sender, EventArgs e)
        {
            CreateHtmlTag("div");//创建一个div
            CreateTable();//创建一个Table控件
            JointHtmlTag();//拼接一个div
        }

        #endregion

        #region 创建HtmlTag

        /// <summary>
        /// 创建Div,br,span等标签通用方法
        /// </summary>
        private void CreateHtmlTag(string htmlTag)
        {
            HtmlGenericControl hgg_div = new HtmlGenericControl(htmlTag);
            hgg_div.Attributes.Add("style", "200px; height:200px; background:#0094ff");
            hgg_div.InnerText = "我是一个" + htmlTag;
            Page.Controls.Add(hgg_div);
        }

        #endregion

        #region 创建Table控件

        /// <summary>
        /// 创建Table控件
        /// </summary>
        private void CreateTable()
        {
            Table newTable = new Table();
            newTable.Width = 200;
            newTable.Height = 200;
            TableRow newTableRow = new TableRow();
            newTableRow.Height = 20;
            TableCell newTableCell = new TableCell();
            newTableCell.Width = 100;
            newTableCell.Text = "我是一个单元格";

            newTableRow.Controls.Add(newTableCell);
            newTableRow.Controls.Add(newTableCell);
            newTable.Controls.Add(newTableRow);
            Page.Controls.Add(newTable);
        }

        #endregion

        #region 字符串拼接HTML

        /// <summary>
        /// 字符串拼接HTML
        /// </summary>
        private void JointHtmlTag()
        {
            string str = "<div style='200px;height:200px;'>我是拼接的div</div>";
            Page.Form.InnerHtml = str;
        }

        #endregion
    }

  

原文地址:https://www.cnblogs.com/Akgu/p/5143833.html