WebForm后端調用前端JS


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebFormBackEndCallFrontJsDemo.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script type="text/javascript">
        function showInfo() {
            alert("Hello World");
        }
    </script>
    <title>WebForm后端調用前端JS</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="方法1" OnClick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="方法2" OnClick="Button2_Click" />
    </form>
</body>
</html>
using System;
using System.Web.UI;

namespace WebFormBackEndCallFrontJsDemo
{
    /// <summary>
    ///     ASP.NET在后台執行前台的js代碼
    ///     LDH @ 2022-1-27
    /// </summary>
    public partial class WebForm1 : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack) Response.Write("<script>alert('Welcome to study asp.net.');</script>");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //  此方法系統會提示已過時,不用管它,一切都正常使用
            Page.RegisterClientScriptBlock("MyScript", "<script defer>javascript:showInfo();</script>");
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterStartupScript(GetType(), "MyScript", "<script defer>javascript:showInfo();</script>");
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM