简体   繁体   中英

ScriptManager.RegisterClientScriptBlock not working in Visual WebPart

I am working in VisualWebPart and want to call Javascript method from c#. Below is my code. If I replace myFunction(); with alert() then alert is working. However, myFunction() is not getting called. I tried with ScriptManager.RegisterStartUpScript too but fail. I debugged and there was no error too. Am I doing anything wrong?

<script type="text/javascript">

    function myFunction() {
        alert('Function called successfully!');
    }
</script>

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"  />

c#
protected void Button1_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "myFunction", "myFunction();", false);
    }

Enable the Script Tags while calling RegisterClientScriptBlock

Here is how: .aspx.cs

protected void Button1_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "myFunction", "myFunction();", true);
    }

.aspx

  <head runat="server">
    <title></title>

    <script type="text/javascript">

        function myFunction() {
            alert('Function called successfully!');
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>
</body>

By providing "true" to the last parameter will make the script to add "Script" tags, then the function will be called accordingly with all validations.

警报讯息

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