0

How can i call a javascript function in the page_load event of a asp.net c# web application

I also want to pass a variable to that javascript function.

3 Answers 3

2

JavaScript is client-side code.

Page_Load is server-side code.

You can't call one directly from the other. The next best thing is to arrange for your client-side code to be called when the page loads in the browser. You can do that by dynamically generating your script in-line with the rest of your markup.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use Page.RegisterStartUpScript

  public void Page_Load(Object sender, EventArgs e)
  {

    if (!this.IsStartupScriptRegistered("Startup"))
    {
      // Form the script to be registered at client side.
      String scriptString = "<script language=\"JavaScript\"> function DoClick() {";
      scriptString += "showMessage2.innerHTML='<h4>Welcome to Microsoft .NET!</h4>'}";
      scriptString += "function Page_Load(){ showMessage1.innerHTML=";
      scriptString += "'<h4>RegisterStartupScript Example</h4>'}<";
      scriptString += "/";
      scriptString += "script>";
      this.RegisterStartupScript("Startup", scriptString);
    }

Comments

0

Depending on your version of .NET you should use

ScriptManager.RegisterStartupScript

the Page level method is deprecated.

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.