Calling a javascript function from Page_Load in code-behind

后端 未结 8 1399
广开言路
广开言路 2021-01-25 03:49

How can I call a javascript function, that is in the aspx page, from the Page_Load method, in the code-behind?

8条回答
  •  我在风中等你
    2021-01-25 03:54

    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 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:

    
    

提交回复
热议问题