如何在aspx页面上使用动态HTML执行服务器端代码 [英] How do I execute server side code with dynamic HTML on aspx page
问题描述
我正在构建一些html并将其分配给div的内部html:
I am building some html and assigning it to the inner html of a div:
private string BuildTab1MiddleCol()
{
StringBuilder buttonStr = new StringBuilder();
buttonStr.Append("<div class=\"w3-col s2a\">");
buttonStr.Append(" <div class=\"w3-container\"> <p>");
buttonStr.Append(" <input type=\"image\" id=\"soft_code\" runat=\"server\" src=\"./Images/checkmarkUnchecked.png\" onserverclick=\"btnTracking_OnClick\" />");
buttonStr.Append(" </p> </div>");
buttonStr.Append(" </div>");
return buttonStr.ToString();
}
当我点击图像时,它会执行Page_Load事件但不执行方法btnTracking_OnClick。
如果我把字符串粘贴在页面本身上:
< input type =imageid =hardCoderunat = serversrc =./ Images / checkmarkUnchecked.pngonserverclick =btnTracking_OnClick/>
btnTracking_OnClick事件触发。
我缺少什么
我的尝试:
通常在网络上追逐答案。
When I click on the image it does execute the Page_Load event but does not execute the method btnTracking_OnClick.
if I take the string and paste it on the page itself:
<input type="image" id="hardCode" runat="server" src="./Images/checkmarkUnchecked.png" onserverclick="btnTracking_OnClick" />
the btnTracking_OnClick event fires.
What am I missing
What I have tried:
The usual chasing of answers up and down the web.
推荐答案
像runat这样的属性只有当它们放在服务器端时才有用控件,即你的标记中的那些控件,比如asp:Image,你正在做的是用runat标签渲染html,所以你把这个属性放在客户端控件上,但是web浏览器不知道该怎么做这样做会忽略它。
如果你想要动态服务ver-side控件必须将它们添加到服务器代码中的容器对象中。谷歌的asp.net创建动态服务器端控件,你会发现很多例子。
Attributes like "runat" only work when they are put on server-side controls, ie ones in your mark-up like "asp:Image", what you are doing is rendering html with the runat tag so you are putting that attribute on the client-side control, but the web browser doesn't know what to do with that so ignores it.
If you want dynamic server-side controls you have to add them to a container object in your server code. Google for "asp.net create dynamic server-side control" and you'll find lots of examples.
看起来他们只能这样做才能使用占位符而不是写到div内部html。所以这个方法现在看起来像这样:
well looks like they only way I could do it was to use placeholder and not write to a div inner html. So the method will now look like this:
private void BuilTab1dMiddleCol(PlaceHolder phHolder, int nhID)
{
string id = "nh_" + nhID;
ImageButton imgBtncheckOff = new ImageButton {ID = id, ImageUrl = "./Images/checkmarkUnchecked.png"};
imgBtncheckOff.Click+= new ImageClickEventHandler(btnTracking_OnClick);
phHolder.Controls.Add(new LiteralControl("<div class=\"w3-col s2a\">"));
phHolder.Controls.Add(new LiteralControl("<div id=\"div_chk \" class=\"w3-container\"> <p>"));
phHolder.Controls.Add(imgBtncheckOff);
phHolder.Controls.Add(new LiteralControl(" </p> </div>"));
phHolder.Controls.Add(new LiteralControl("</div>"));
}
这篇关于如何在aspx页面上使用动态HTML执行服务器端代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!