<%@ 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后端调用前端JStitle>
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
{
///
/// ASP.NET在后台执行前台的js代码
/// LDH @ 2022-1-27
///
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>");
}
}
}