Calling a javascript function from Page_Load in code-behind

后端 未结 8 1201
广开言路
广开言路 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 <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>
    
    0 讨论(0)
  • 2021-01-25 03:55

    You need to use Register client Script:

    • MSDN

    • CodeProject

    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).

    0 讨论(0)
  • 2021-01-25 03:56

    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.

    0 讨论(0)
  • 2021-01-25 03:56

    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

    0 讨论(0)
  • 2021-01-25 04:06

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

    0 讨论(0)
  • 2021-01-25 04:16

    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.

    0 讨论(0)
提交回复
热议问题