Reputation: 971
I have a webpage (ASP.NET C#) that has a button:
<asp:Button ID="btnHide" runat="server" OnClick="HidePanel" Text="Hide"/>
and I'm doing a JavaScript alert like:
public void HidePanel(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),"Hello","<script type=text/javascript> alert('Hello') </script>");
}
If I modify the function to not have object sender
and EventArgs e
then I can call it from Page_Load
, and it works fine, I get the alert.
As written above I expect to see the alert when I click the button, but it's not happening. I'm sure it's something obvious, but I don't see it.
Upvotes: 1
Views: 1875
Reputation: 11317
You can remove the code to register the JavaScript code and instead do this:
<asp:Button ID="btnHide" runat="server"
OnClick="HidePanel" Text="Hide" OnClientClick="alert('Hello');"
UseSubmitBehavior="false" />
This:
UseSubmitBehavior="false"
will cause the button to fire the client-side script, and it will run the server-side code (post-back).
Upvotes: 1
Reputation: 678
You could try using, ClientScript.RegisterClientScriptBlock(GetType(), "nameOfScript", scriptString);
I'ved used that before in a click event.
edit: I can't edit posts yet, but your code works fine for me as well.
And depending on the situation he might want to do some server side stuff as well on the click event, or build up the script dynamically.
Edit: If you already registered a script with the same name, it won't run, eg.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Hello", "<script type=text/javascript> var i = 0;</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "Hello", "<script type=text/javascript> alert('other hello') </script>");
Upvotes: 2
Reputation: 86
Use OnClientClick
instead of OnClick
. And add a return false
to avoid a postback on the page.
<asp:Button ID="btnHide" runat="server" OnClientClick="alert('Hello'); return false;" Text="Hide"/>
Upvotes: 3