Adding OnClick event to ASP.NET control

前端 未结 3 2076
温柔的废话
温柔的废话 2021-01-15 08:06

i would like to create OnClick event for my panel. So far now the most of the google results look more or less like this: adding onclick event to a

相关标签:
3条回答
  • 2021-01-15 08:12

    In your java script method raise a __dopostback call to a Server side method.

    <script type="text/javascript">
         function YourFunction()
         {
             __doPostBack('btnTemp', '')
         }
    </script>
    

    Where btnTemp is a server side button, so write a onClick event of this button on server side, where you can do the processing and then redirect to other page.

    You can have a good understanding of dopostback at DoPostBack Understanding

    0 讨论(0)
  • 2021-01-15 08:16

    There is a PostBackUrl property on a ASP.NET Button, you could render the button as normal then postback to a different page - this is where your OnClick method would need to be declared.

    I would strongly recommend against posting back to the same page then doing a Response.Redirect(), consider the traffic. The browser requests the page, posts back then is sent a HttpRedirect and then navigates to the new page. With the method I have outlined above this is not required and the browser has to make one request less (meaning the message doesn't have to be sent or the page rebuilt on the server) and is a significant performance benefit.

    0 讨论(0)
  • 2021-01-15 08:26

    My aspx page is like:

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <script type="text/javascript">
            function CallMe() { __doPostBack('btnTemp', '') }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
             <asp:Button ID="btnTemp" runat="server" Text="Test" onclick="btnTemp_Click" />
             <div> <asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
             <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
        </form>
    </body>
    

    And my Server Side code is as:

    protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Attributes.Add("onClick", "CallMe();");
        }
    protected void btnTemp_Click(object sender, EventArgs e)
        {
    
        }
    

    Thats the code that I have written, I haven;t included the using statement, Page directive etc in above code.

    0 讨论(0)
提交回复
热议问题