Oak
Oak

Reputation: 1169

Adding OnClick event to ASP.NET control

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 aspnet label. Is there any way, to call codebehind function from javascript or panel attributes? Because I would like to Redirect user to a new page and before that save some information in ViewSTate or Sessionstate. Any suggestions?

Upvotes: 2

Views: 44157

Answers (3)

Imran Balouch
Imran Balouch

Reputation: 2170

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.

Upvotes: 2

Imran Balouch
Imran Balouch

Reputation: 2170

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

Upvotes: 2

Liath
Liath

Reputation: 10191

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.

Upvotes: 0

Related Questions