.NET 前台后台方法相互调用 HTML Code
.NET 前台后台方法相互调用 HTML Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>前台后台方法相互调用</title>
<%--
JavaScript异步调用定义在ASP.NET页面中的方法,需要:
1.该方法声明为公有( public );
2.该方法声明为静态(类方法 static)
3.该方法添加[WebMethod]属性;
4.添加using System.Web.Services;
5.页面中ScriptManager控件的EnablePageMethods属性认为true;
6.在客户端使用如下JavaScript语法调用页面方法:
PageMethods.[MethodName](param1,param2,...,CallBackFunction);
7.为客户端调用指定回调函数,在回调函数中接受返回值并进一步处理
--%>
<%--
ASP.NET后台调用JavaScript function方法,要注意:
1.尽量少用Response.Write(<script></script>);这种方法会影响CSS导致页面效果偏差
2.C#中使用ScriptManager.RegisterStartupScript(this,this.GetType(),"","JScode",true);
3.添加 using System.Web.UI;
--%>
</head>
<body>
<script type="text/javascript">
/*-----------JavaCript 调用.NET后台 start-------------*/
function JsCallCSharp(param) {
PageMethods.SayHelloFromPage(param, OnSayHelloSucceeded);
}
/*------------回调函数--------------*/
function OnSayHelloSucceeded(result) {
alert(result);
}
/*-----------JavaCript 调用.NET后台 end---------------*/
/*---------.NET调用JavaScript start--------*/
function CSharpCallJs(param1, param2) {
alert(param1 + param2);
}
/*----------.NET调用JavaScript end-------*/
</script>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:Button ID="btnTemp" runat="server" OnClientClick="JsCallCSharp('Jay Wang');" OnClick="OnClick" Text="Click Me!"/>
</div>
</form>
</body>
</html>
C# Code
using System;
using System.Web.UI;
using System.Web.Services;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string SayHelloFromPage(string name)
{
return string.Format("Hello {0}!", name);
}
protected void OnClick(object sender, EventArgs e)
{
string param1 = "你好!";
string param2 = "Jay Wang";
ScriptManager.RegisterStartupScript(this, this.GetType(), "edit", "CSharpCallJs('" + param1 + "','" + param2 + "');",true);
}
}