【发布时间】:2011-12-15 00:21:22
【问题描述】:
我正在测试两个 ImageButton 控件,一个是在 GridView_RowDataBound 函数中以编程方式设置的,另一个在客户端硬编码如下:
静态 ImageButton(工作并触发 ImageButton_Click):
<asp:ImageButton OnClick="ImageButton_Click" runat="server" ID="Foo" ImageUrl="images/edit-icon.png" />
动态 ImageButton(不起作用,不会触发 ImageButton_Click):
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
.
.
.
ImageButton i = new ImageButton();
i.ImageUrl = "/images/edit-icon.png";
i.ID = "icon_" + testID.ToString();
i.ToolTip = "Click to add a new comment";
i.Click += new ImageClickEventHandler(ImageButton_Click);
e.Row.Cells[5].Controls.Add(i);
.
.
.
}
Dynamic ImageButton 呈现如下
<input type="image" name="GridView1$ctl24$DGV1$ctl02$icon_1234" id="GridView1_ctl24_DGV1_ctl02icon_1234" title="Click to add a new comment" src="/images/edit-icon.png" onclick="ImageButton_Click;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("GridView1$ctl24$DGV1$ctl02$icon_1234", "", true, "", "", false, false))" style="border-width:0px;">
我注意到动态图像按钮包含“onclick”与具有“OnClick”的静态图像按钮,不确定这是否会有所不同。在过去的几个小时里,我一直对此感到困惑,我不知道为什么动态 ImageButton 没有触发。请帮忙。
更新:
感谢所有反馈,我只需要处理 ImageButton 的 ID,它不必是服务器端的。无论如何我可以使用 JavaScript 从客户端执行此操作以避免回发?我尝试重新配置 ImageButton 如下:
ImageButton i = new ImageButton();
i.ImageUrl = "/images/edit-icon.png";
i.ID = "icon_" + testID.ToString();
i.ToolTip = "Click to add a new comment";
i.OnClientClick = "submitComment(i.ID);return false;";
e.Row.Cells[5].Controls.Add(i);
我在我的网络表单的标题中指定了这个函数
<head runat="server">
<script type="text/javascript">
submitComment(i.ID){
//Call WebMethod and pass comment along with this button's testID
}
</script>
</head>
但是当我点击编辑图标 ImageBtn 时出现以下错误:
Uncaught Reference Error: icon_12345 is not defined.
这是怎么回事?如果编辑图标已经呈现并且我只是使用客户端 Javascript,那么它们不应该已经被定义并且能够被正确引用吗?这对我来说似乎非常违反直觉。我在这里错过了什么吗?除了 ImageButton 之外,是否还有其他控件可以用于渲染图像而不必担心回发,但它仍然可以调用 Javascript 并传递它的 ID?使用常规的 Image 控件并连接它的 onclick 属性来调用 submitComment 函数怎么样?
【问题讨论】:
-
我也遇到了这个问题。在调用 page_load 函数后,您似乎无法将 EventHandler 添加到按钮,因为 .NET 不会正确注册它们。你可以在Page_Init中添加它,但是你不能在RowDataBound函数中动态绑定它,这也是我要做的。
-
Jay Douglass 说你是在通过使用这种技术来寻求痛苦和折磨是正确的。应该没必要吧。如果你给我们更多来自
gv_RowDataBound()的代码来显示你为什么要动态创建ImageButton,我可能会提出一种替代方法来完成相同的任务,而无需在每次回发时动态创建控件。
标签: c# asp.net ajax web-applications webforms