今天在写下面的代码时遭遇错误——“System.Web.UI.WebControls.Literal”不允许使用子控件('System.Web.UI.WebControls.Literal' does not allow child controls):
var postBodyDiv = new HtmlGenericControl(){ ID = "cnblogs_post_body", ClientIDMode = ClientIDMode.Static, TagName = "div", InnerHtml = body};var signatureDiv = new HtmlGenericControl(){ ID = "signature", TagName = "div"};literalBody.Controls.Add(postBodyDiv);literalBody.Controls.Add(signatureDiv);
literalBody的类型是System.Web.UI.WebControls.Literal。将postBodyDiv与signatureDiv作为子控件添加到literalBody中,是为了避免字符串拼接带来的内存消耗。
之前字符串拼接的代码如下:
literalBody.Text = "" + body + "";
本来这不是问题,把类型由Literal改为Label就行了,但是实际场景不允许这么做,必须要用Literal。
后来采取了在literalBody的父控件中动态添加postBodyDiv与signatureDiv的方法解决了问题,代码如下:
var postBodyDiv = new HtmlGenericControl(){ ID = "cnblogs_post_body", ClientIDMode = ClientIDMode.Static, TagName = "div", InnerHtml = body};var signatureDiv = new HtmlGenericControl(){ ID = "signature", TagName = "div"};var bodyControlIndex = this.Controls.IndexOf(literalBody);if (bodyControlIndex >= 0){ Controls.AddAt(bodyControlIndex, postBodyDiv); Controls.AddAt(bodyControlIndex + 1, signatureDiv);}