在我實際開發過程當中,恰好遇到c#後端要調用前端js中的方法,因此研究了一下,特分享以下:javascript
前端代碼:html
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="netToWebFantion.aspx.cs" Inherits="WebApplication2.netToWebFantion" %> <!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 webfunction(par) { alert("後端調用前端的方法:"+ par); return false; } </script> <title>c#後端調用前端的方法</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="net"/> </div> </form> </body> </html>
後端代碼:前端
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication2 { public partial class netToWebFantion : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void net(object sender, EventArgs e) { ClientScript.RegisterStartupScript(this.GetType(), "par", "<script>webfunction('你好嗎!')</script>");//webfunction('par')是前臺jquery函數 } protected void Button1_Click(object sender, EventArgs e) { } } }
核心的代碼就是後端:ClientScript.RegisterStartupScript(
this
.GetType(),
"par"
,
"<script>webfunction('你好嗎!')</script>"
);
java