views:

300

answers:

5

hi friends

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.

+2  A: 

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.

RickNZ
A: 

I think what you are looking like is, in the page load you want to add javascript funcation of some server control....

button1.Attributes.Add("onclick", "javascript:yourfunctionName(parameterValue);");
Muhammad Akhtar
+2  A: 

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);
    }
jerjer
A: 

Depending on your version of .NET you should use

ScriptManager.RegisterStartupScript

the Page level method is deprecated.

MattC