我试图在 asp.net 中动态创建一个表单,并通过在呈现的控件上执行文本替换将其呈现在页面上。
(我不能只将控件推送到页面上的面板,那是理想的情况,我现在不会遇到这个问题)/p>
我创建了一个标签、文本框和一个按钮,并将它们全部添加到面板中。然后使用 TextWriter 将此面板呈现为字符串,然后我使用它对我的副本执行替换。
Label lbl = new Label();
lbl.Text = "Enter Amount";
lbl.Attributes.Add("style", "width:25%; vertical-align:middle;");
lbl.CssClass = "donate-label";
lbl.ID = "lblAmount";
TextBox tb = new TextBox();
tb.ID = "tbAmount";
tb.Attributes.Add("style", "padding-left:25px; width:50%;");
lbl.AssociatedControlID = tb.ID;
Button b = new Button();
b.ID = "btnDonate";
b.Text = "Make a Donation";
b.CssClass="block-btn right-arrow red-bg right";
b.Click += new EventHandler(btnDonate_Click);
b.Attributes.Add("style", "display:table-cell; margin-top:0; width:40% !important;");
Panel pnlForm = new Panel();
pnlForm.CssClass="form clearfix donate-form";
pnlForm.Attributes.Add("style", "width:70%");
pnlForm.Controls.Add(lbl);
pnlForm.Controls.Add(tb);
pnlForm.Controls.Add(b);
现在,如果我要将上面的面板添加到页面上已经存在的面板,它会按预期完美地工作,但控件呈现导致它在某处中断..
TextWriter myTextWriter = new StringWriter();
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);
pnlForm.RenderControl(myWriter);
string body = p.Copy.Replace("##donate##", myTextWriter.ToString());
我得到的错误如下:
无法找到与标签“lblAmount”关联的 ID 为“tbAmount”的控件。
第 146 行:pnlForm.RenderControl(myWriter);
如果我删除了我的标签的 assoicatedControlID 它工作正常,但不幸的是它将我的标签呈现为一个跨度,这不是我需要的,我需要它呈现为带有“for”属性的标签。
最佳答案
最简单的方法是使用带有 html 标签的文字
Literal lbl = new Literal();
lbl.Text = "<Label For='tbAmount' style='width:25%; vertical-align:middle;' class='donate-label' > Enter Amount </label>";
lbl.ID = "lblAmount";
顺便将 tbAmount id 设为静态,这样您就不会为您的文本框获得任何不可预知的 id
tb.ClientIDMode= System.Web.UI.ClientIDMode.Static
关于c# - 使用面板 RenderControl 方法时无法找到具有 id 的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26103783/