简体   繁体   中英

Calling a javascript function from Page_Load in code-behind

如何在代码隐藏中从 Page_Load 方法调用 aspx 页面中的 javascript 函数?

The simple answer is, you can't. The code in the Page_Load method executes on the server, javascript executes on the client.

If what you want to do is add a call to a javascript method, in the Page_Load so that once the page is loaded by the browser, the javascript executes, then you can use the ScriptManager:

if (myConditionForAddingCallToJavascriptIsMet)
{
    Page.ClientScript.RegisterClientScriptBlock(typeof(ScriptManager), "CallMyMethod", "myMethod();");
}
else
{
    // Do something else, add a different block of javascript, or do nothing!
}

To use this, you'll need to have an <asp:ScriptManager> element in your markup for it to use (if memory serves, an exception will be thrown if you don't have one). The text "CallMyMethod" is used by the ScriptManager to uniquely identify the script that it injects for you, and the text "myMethod();" is embedded, so you'll end up with an additional script element in your page similar to this:

<script language="javascript" type="text/javascript">
    myMethod();
</script>

The easiest way is to use the page's ClientScript property. You can register some code to run when the page loads using something like

ClientScript.RegisterStartupScript(GetType(), "hiya", "alert('hi!')", true);

See http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx for more info.

This should be available from a child control by tacking "Page." onto the beginning of the code above.

Why would you want to do this? What's the purpose?

Anyway you can do the following, but I DON'T recommend it !!! :

     protected void Page_Load(object sender, EventArgs e)
    {
         string pagename = "Test.aspx"; 
         String scriptString = "<script language=JavaScript> function DoClick() {"; 
         scriptString += " window.showModalDialog('" + pagename + "' )}"; 
         scriptString += "</script>";            

if(!this.IsStartupScriptRegistered("Startup")) //This is **not** a good practice
this.RegisterStartupScript("Startup", scriptString); 
    }

Can you supply with more information of what you want to achieve to get better answer..

Shide's solution works. The problem is if you want to run your piece of code only on postback, for example. The solution I found was to use a "cookie": I verify if cookie x exists, if it doesn't I run the javascript code and set the cookie. When you hit refresh, the cookie will be found so the piece of code won't run.

function pageLoad() {
   if(localStorage.getItem("cookie") === null) {
      localStorage.setItem("cookie", true);

      //run code
   }
}

Any code you need to run every single time just leave it out of the if statement.

If you just want to call a JavaScript function ( and do not need to pass something from code-behind, then use this...)

  • document.onload = function () { your-function(); };

  • window.onload = function () { your-function(); };

  • document.readyState = function () { your-function(); }

    ... depending on your specific requirements.

Hope this makes sense to you & answers your question.

this is a little trick i found myself without having server side code . that function will be called when the page loads (can be used with an update panel) :

<script>
function pageLoad() {
        //Do your stuff
        }
</script>

it is unknown and yet works like a charm

请试试这个代码:

  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "test();", true);

You need to use Register client Script:

I do it in a Page Load method:

if (!this.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "HelpScript"))
{
  var scriptSource = "function ShowHelp() { alert(""); };\n";
  ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "HelpScript", scriptSource, true);
}

but I don't think it's recommended

I mean... you can do this, and it'll work. But for me the only good reason of inserting a script from asp.net page is to get some client side features of server controls.

So for example to get an instance of control:

var myControlId = this.control.ClientID;

But writing entire javascript functions and logic on the server side is not comfortable when you need to change it or debug it (for me it's hardcoded string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM