Calling a javascript function from Page_Load in code-behind

后端 未结 8 1204
广开言路
广开言路 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: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).

提交回复
热议问题