1

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.

1
  • I am using OnClick because there is a lot more that has to happen such as checking connectivity and current session with a 3rd party reservation system we use. Commented Feb 20, 2012 at 20:23

3 Answers 3

3

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"/>
Sign up to request clarification or add additional context in comments.

2 Comments

There's a lot of steps that have to happen in the server side. If I do this can I get it to run my server scripts after the js handles the click event if I don't have an onclick?
Just add the OnClick back and add your server side code on the OnClick method. But leave the alert on the OnClientClick and remove the return false so that the page postsback and executes your server side code. This will make the alert popup and when you click ok the page will postback and your server side will execute.
2

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>");

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.