locked
execute javascript from code behind? RRS feed

  • Question

  • User-125499312 posted

    how do <g class="gr_ gr_9 gr-alert gr_tiny gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" id="9" data-gr-id="9">i</g> execute javascript from code behind?

    thx for ur help

    Wednesday, February 6, 2019 7:19 PM

All replies

  • Wednesday, February 6, 2019 9:04 PM
  • User-1174608757 posted

    Hi yzidell,

    I suggest you to use ClientScript.RegisterStartupScript in code behind , so you could easily execute javascript  defined in front end or just written in code behind. Here is the demo , I hope it could help you.

    js defined in front end:

    aspx:

    <head runat="server">
        <title></title>
    <script>
        function MyFunction()
        {
            alert("this is definded in front end")
    
        }
    
    </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            </div>
        </form>
    </body>
    </html>
    

    aspx.cs:

      public partial class Script : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
               
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "MyFunction()", true);
    
            }
        }

    It shows as below:

    When defined just in code behind:, you could write as below:

     public partial class Script : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
               
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "alert('defined in code behind')", true);
    
            }
        }

    Best Regards

    Wei Zhang

    Thursday, February 7, 2019 3:00 AM