【发布时间】:2016-08-15 20:42:24
【问题描述】:
调用在运行时动态构建 HTML 元素并将呈现的元素作为字符串返回的 Web 服务时出现异常。
RenderControl()方法调用出现如下错误:
System.Web.HttpException:找不到与标签“lblCertificate”关联的 ID 为“txtCertificate”的控件。
StringWriter stringWriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringWriter);
// Create System.Web.UI.WebControls.Panel (container)
Panel pnlFRow1 = new Panel();
pnlFRow1.CssClass = "f-row";
// Create System.Web.UI.WebControls.Textbox
TextBox txtCertificate = new TextBox();
txtCertificate.ID = "txtCertificate";
txtCertificate.CssClass = "f-input f-input-full";
// Create System.Web.UI.WebControls.Label
Label lblCertificate = new Label();
lblCertificate.ID = "lblCertificate";
lblCertificate.CssClass = "f-label f-label-full";
lblCertificate.AssociatedControlID = txtCertificate.ID;
lblCertificate.Text = "Certificate:";
Panel pnlCertificate = new Panel();
pnlCertificate.CssClass = "f-label f-label-full";
// Binding child controls to parent controls
pnlFRow1.Controls.Add(lblCertificate);
pnlFRow1.Controls.Add(pnlCertificate);
pnlCertificate.Controls.Add(txtCertificate);
// Render control
pnlContent.RenderControl(writer);
// Return rendered HTML
return writer.InnerWriter.ToString();
我尝试将pnlFRow1.Controls.Add(lblCertificate); 行放在pnlCertificate.Controls.Add(txtCertificate); 行之后,认为这可能是顺序很重要的问题,但这会导致相同的错误。
AssociatedControlID 属性是必须具备的,以便将Label WebControl 呈现为实际的<label> 元素,并且必须在输入控件之前显示。
【问题讨论】:
标签: c# .net rendering web-controls