C#在后台程序中动态创建HTML标签(div,span,a,p等)

案例代码如下:
1,创建div、span、a标签时,核心是用了System.Web.UI.HtmlControls命名空间下的HtmlGenericControl类
2,如果要创建input标签,要用HtmlInputText类

HtmlGenericControl divList = new HtmlGenericControl("div");

if (dsrow["ReadFlag"].ToString() == "已读")
{
    divList.Attributes.Add("class", "list read");
}
else
{
    divList.Attributes.Add("class", "list");
}
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes.Add("href", msg_url);
divList.Controls.Add(a);

HtmlGenericControl divMeta = new HtmlGenericControl("div");
divMeta.Attributes.Add("class", "meta");

HtmlGenericControl spanSort = new HtmlGenericControl("span");
spanSort.Attributes.Add("class", "sort " + sorttype + "");
spanSort.InnerText = dsrow["msg_typename"].ToString();
divMeta.Controls.Add(spanSort);

HtmlGenericControl spanStatus = new HtmlGenericControl("span");
spanStatus.Attributes.Add("class", "status");
spanStatus.InnerText = dsrow["ReadFlag"].ToString();
divMeta.Controls.Add(spanStatus);

a.Controls.Add(divMeta);

HtmlGenericControl divTitle = new HtmlGenericControl("div");
divTitle.Attributes.Add("class", "title");
divTitle.InnerText = dsrow["msg_title"].ToString();

a.Controls.Add(divTitle);

HtmlGenericControl divInfo = new HtmlGenericControl("div");
divInfo.Attributes.Add("class", "info");

HtmlGenericControl spanMan = new HtmlGenericControl("span");
spanMan.Attributes.Add("class", "man");
spanMan.InnerText = DeptName + " · " + UserName;
divInfo.Controls.Add(spanMan);

HtmlGenericControl spanTime = new HtmlGenericControl("span");
spanTime.Attributes.Add("class", "time");
spanTime.InnerText = dsrow["Push_date"].ToString();
divInfo.Controls.Add(spanTime);

a.Controls.Add(divInfo);

dataBind.Controls.Add(divList);

要点:
1,要创建html标签,找到对应的类,new一个对象出来即可
2,对象名称.Attributes.Add("属性名称","属性值")添加class、href等属性
3,对象名称.InnerText = "标签的文本内容"
4,对象名称.Controls.Add(子标签名称),这个用来实现HTML标签嵌套、层级关系。

添加新评论