简体   繁体   中英

How to run javascript from c# in asp.net

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.

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>

First of all, I don't understand why you are using the ScriptManager here. An ASP Button has a property named onClientClick . See this MSDN link for more information.

You can change your button's code in the HTML like:

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

Note: The onClientClick will be executed before the onClick event. This is written out of my head and untested!

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