How to run javascript from c # in asp.net

I am new to Asp.Net and I have an aspx page like this

<%@ Page Title="" Language="C#" MasterPageFile="~/Main.Master" AutoEventWireup="true" CodeBehind="TestJs.aspx.cs" Inherits="tms.Test.TestJs" %>

<asp:Content ID="Content1" ContentPlaceHolderID="StyleSection" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentSection" runat="server">
    <div class="container">
        <div class="panel">
            <asp:Button ID="btnAlert" OnClick="btnAlert_OnClick" runat="server"/>
        </div>
    </div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ScriptSection" runat="server">
    <script type="text/javascript">
        function myFunc() {
            $.alert("Hello Mz");
        }
    </script>
</asp:Content>

And my .cs file looks like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace tms.Test
{
    public partial class TestJs : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnAlert_OnClick(object sender, EventArgs e)
        {
            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "newFunc", "myFunc()", true);
        }
    }
}

When I click the button, the script is not called and does not give the expected error of the object.

I am really stuck with this. Please help me. Thanx In Advance.

+4
source share
2 answers

If you click the click scriptmanager, you can call

protected void btn_click(object sender, EventArgs e){
ScriptManager.RegisterStartupScript(this,this.GetType(),"Your Comment","myFunc();", true);}

Modify the script as shown below:

<script type="text/javascript">
    function myFunc() {
        alert("Hello Mz");
    }
</script>
+2
source

First of all, I do not understand why you are using ScriptManagerhere. The ASP button has a property with a name onClientClick. For more information, see MSDN Link .

You can change the button code in HTML, for example:

<asp:Button ID="btnAlert" OnClick="btnAlert_OnClick" onClientClick="myFunc();" runat="server"/>

: onClientClick onClick. !

+1

All Articles