1

Using ASP.NET 4.0 (c#), I want to call a button's OnClientClick event from code-behind (server-side). How do I code that in the code-behind file so that when the page is rendered again, the OnClientClick event is fired like the user clicked the button?

2 Answers 2

1

Here are two ways to "call" the javascript alert function from code behind. You may be able to replace the alert function with your function:

public static void ShowAlert(Page page, String message)
{
    String Output;
    Output = String.Format("alert('{0}');",message);
    page.ClientScript.RegisterStartupScript(page.GetType(), "Key", Output, true);
}

public static void ShowAlert(HttpResponse response, String message)
{
    String Output;
    Output = String.Format("<Script Language='javascript'> alert('{0}');</script>", message);
    response.Write(Output);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Add a little JQuery to the page...

<head>
  <!-- Add the jquery library to your page -->
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>          

  <!-- Document.ready runs when the page is loaded -->
  <script type="text/javascript">                                         
    $(document).ready(function () {
      $('#MyButtonID').click();  // Find the button and click it.
    });
  </script>                                                               
</head>

2 Comments

Isn't there some way to call the button's click event from the code-behind to fire when the page renders?
Server side code has no control over what happens on the client. They are completely disconnected. So you need to write client-side code to accomplish this. My suggestion and Steve's are two ways of doing the same thing, adding Javascript code to the page. My recommendation is to jump right in and use JQuery, it'll open a whole new world of what you can accomplish when you have complete control of the client side as well.

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.