Search code examples
javascriptasp.netvb.netonclientclick

OnClick/OnClientClick event with Asp.Net


I am a little confused to use this script and how it actually works?

Here is my script:

 <script type="text/javascript">
        $(document).ready(function () {
            $('#<%=TextBox1.ClientID%>').change(function () {
                $('#various3').attr('href', $(this).val());
            });


                $("#<%=Button1.ClientID%>").click(function (event) {
                    setTimeout(showStickySuccessToast, 1000);
                    function showStickySuccessToast() {
                        $().toastmessage('showToast', {
                            text: 'Finished taking Screenshot!',
                            sticky: false,
                            position: 'middle-center',
                            type: 'success',
                            closeText: '',
                            close: function () {

                            }
                        });
                    }

                })                
        });
      </script>

This is my button:

<a id="various3" href="#"><asp:Button ID="Button1" runat="server" 
    Text="Button" OnClientClick="Button1_Click"/></a>

This is my code behind for button1_Click event:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim NewTh As New Threading.Thread(AddressOf DoIT)
    NewTh.SetApartmentState(Threading.ApartmentState.STA)
    NewTh.Start()
    ImgPreview.ImageUrl = "~/uploads/Sample.jpg"
End Sub

Now if I click the button it should open the iframe and display the message which I am able to do. Now the problem is how do I call the button1_Click event which is in the codebehind at the same time. I have used OnClick and OnClientClick event as shown below but it's not working and I'm not getting any errors.


Solution

  • It looks like you've got things backwards:

    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" />
    

    The above example assumes that Button1_Click is the code-behind click event handler. Since you're assigning the client click event in jQuery, you shouldn't need to use OnClientClick at all.

    EDIT

    I would check to make sure that validation isn't intefering with the click. You can test this by setting CausesValidation="false" on the Button.