简体   繁体   中英

ImageButton OnClick event not working in asp.net

I have an Imageutton in asp.net. I want when I clicked on it, an event fire (that code of this event is written in c#).

asp code is:

<div align="right">
    <table dir="rtl">
        <tr>
            <td>
                <asp:ImageButton ID="imgScoreStar1" runat="server" ImageUrl="~/Images/ScoreStars/Star0_28px.png" OnClick="Star_Onclick" />
            </td>
        </tr>
    </table>
</div>

and behind code is:

protected void Star_Onclick(object sender, ImageClickEventArgs e)
{
    //do something
}

but ever fire click event (I tested it by breakpoint).

Another question: When I click on ImageButton, postback happens. how can I avoid this?

Thank.

Few things to check: 1. Check CausesValidation property. Test with making it false. 2. Use Page.RegisterRequiresRaiseEvent(ImageButton)

How to avoid postback.

  1. Add ScriptManager. There must be only one ScriptManager in one page. (If you are using Master page, add to master page and no need to add anymore in nested content page)

  2. Add UpdatePanel and add your desired content including imagebutton to ContentTemplate of UpdatePanel.

in aspx

<asp:ScriptManager runat="server"></asp:ScriptManager>
        <asp:UpdatePanel runat="server">
            <ContentTemplate> 
  <div align="right">
        <table dir="rtl">
            <tr>
                <td>
                    <asp:ImageButton ID="imgScoreStar1" runat="server" ImageUrl="~/Images/ScoreStars/Star0_28px.png" OnClick="Star_Onclick" />
                </td>
            </tr>
        </table>
    </div>
 </ContentTemplate>
        </asp:UpdatePanel>

in cs

protected void Star_Onclick(object sender, ImageClickEventArgs e)
{
    //do something
}

i checked its working you need to check property of that button try to add another button and change ID of button that will Ignore the property that are stopping click event

You can surround your Page load sequence like this...

if(!IsPostBack){

//PageLoad code

}

Then write code under the button click event. The button click event should work

It worked for me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM