Adding OnClick event to ASP.NET control

*爱你&永不变心* 提交于 2019-12-01 11:46:12
Imran Balouch

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!