How to run javascript from c# in asp.net

Murtaza Munshi picture Murtaza Munshi · Jun 2, 2015 · Viewed 8.2k times · Source

I am new to Asp.Net and i have my 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 does not call up and give some object expected error.

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

Answer

Rakesh Sajja picture Rakesh Sajja · Jun 2, 2015

In the button click event scriptmanager can be called

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

Change your script like below :

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