我是asp.net的新手。
我正在尝试使用ImageButton链接到另一个页面。 ImageButton位于Repeater中,代码如下:
<ul id = "ulMap">
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<li>
<asp:ImageButton ID="ImageButton1"
CommandArgument='<%#Eval("Nav_ID") %>'
runat="server"
ImageUrl="~/Icons/Ny_mappa.png"
onclick="ImageButton1_Click" />
<br />
<asp:LinkButton ID="lnkButton"
CommandArgument='<%#Eval("Nav_ID") %>'
runat="server"
onclick="LinkButton3_Click"
Text='<%#Eval("Nav_Name") %>'></asp:LinkButton>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
背后的代码如下:
protected void LinkButton3_Click(object sender, EventArgs e)
{
Guid guid = new Guid(((LinkButton)sender).CommandArgument);
var query = from n in dc.Nemanet_Navigations
where n.UserId == userGuid && n.Nav_pID == guid
orderby n.Nav_Name ascending
select n;
Repeater1.DataSource = query;
Repeater1.DataBind();
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Guid guid = new Guid(((ImageButton)sender).CommandArgument);
var query = from n in dc.Nemanet_Navigations
where n.UserId == userGuid && n.Nav_pID == guid
orderby n.Nav_Name ascending
select n;
Repeater1.DataSource = query;
Repeater1.DataBind();
}
好吧,对于LinkButton
,这种方法很好但不适用于ImageButton
。 Protected void ImageButton1_Click
永远不会发生。有人可以帮忙吗?
答案 0 :(得分:3)
我很瘦,你需要处理Repeater_ItemCommand事件才能使其正常工作。它也可能会节省一些代码。
另外,如果您要链接到另一个页面,是否需要回发到页面然后执行某种重定向,或者在新页面中使用该逻辑会更有意义吗?
答案 1 :(得分:2)
而不是OnClick,你应该OnCommand。像这样。
<ul id = "ulMap">
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<li>
<asp:ImageButton ID="ImageButton1"
CommandArgument='<%#Eval("Nav_ID") %>'
runat="server"
ImageUrl="~/Icons/Ny_mappa.png"
OnCommand="ImageButton1_Click" />
<br />
<asp:LinkButton ID="lnkButton"
CommandArgument='<%#Eval("Nav_ID") %>'
runat="server"
OnCommand="LinkButton3_Click"
Text='<%#Eval("Nav_Name") %>'></asp:LinkButton>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
这个(注意CommandEventArgs而不是EventArgs和ImageClickEventArgs):
protected void LinkButton3_Click(object sender, CommandEventArgs e)
{
Guid guid = new Guid(e.CommandArgument);
var query = from n in dc.Nemanet_Navigations
where n.UserId == userGuid && n.Nav_pID == guid
orderby n.Nav_Name ascending
select n;
Repeater1.DataSource = query;
Repeater1.DataBind();
}
protected void ImageButton1_Click(object sender, CommandEventArgs e)
{
Guid guid = new Guid(e.CommandArgument);
var query = from n in dc.Nemanet_Navigations
where n.UserId == userGuid && n.Nav_pID == guid
orderby n.Nav_Name ascending
select n;
Repeater1.DataSource = query;
Repeater1.DataBind();
}
答案 2 :(得分:1)
您无法像这样处理转发器子控件的服务器端事件。
以这种方式思考 - 如果有100个按钮,则每个按钮需要100个事件处理程序。 ImageButton1_Click
仅适用于ID为1的ImageButton。
答案是为您的转发器连接ItemCommand
事件。
像这样:
<asp:repeater id = "Repeater`" runat = "server" onItemCommand = "SomeEvent">
然后为触发此事件的所有按钮处理“SomeEvent”:
protected void SomeEvent ( Object src, RepeaterCommandEventArgs e ) {
var whoClickedMe = ((ImageButton) e.CommandSource );
}
Here's关于这样做的好文章。