/*注意:定义的js方法一定要放在head里面,不能放下面,否则不生效*/
<%@ 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>"); } } }
转至:WebForm后端调用前端JS - Love In Winter - 博客园 (cnblogs.com)
标签:后端,void,object,EventArgs,JS,WebForm,Page From: https://www.cnblogs.com/SmallChen/p/17751413.html