我正在测试两个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);
.
.
.
}
动态 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来实现这一点,以避免postback?我尝试重新配置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之外,还有其他控件可以用于渲染图像而无需担心PostBack,并且仍然可以调用JavaScript并传递其ID吗?使用普通的Image控件,将其onclick属性连接到submitComment函数会怎样?
gv_RowDataBound()
中提供更多代码,以显示为什么需要动态创建ImageButton
,我可能会提出一种替代方法,在每次回发时都无需动态创建控件即可完成相同的任务。 - pseudocoder