您的位置:首页 > 其它

Web Service 与 PageMethods 初步认识

2009-09-19 21:20 169 查看
我来介绍一下PageMethods 这个方法的使用 使用前首先要启用 启用方法如下:
<asp:scriptManager ID="scriptManager1" runat="server" EnablePageMethods="True" /> EnablePageMethods 一定会要设为true,
这样我门才能在 客户端调用服务器的方法 下面有个详细的例题

在 客户端代买如下
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
function GetServerTime() {
PageMethods.GetServerTime();//这个方法就是 服务器的方法
}
// ]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:scriptManager ID="scriptManager1" runat="server" EnablePageMethods="True" />
<div>
<input type="button" value="服务器时间" id="btnGetServerTime" onclick="GetServerTime()" />
<span id="result" />
</div>
</form>
</body>
</html>

下面 后置文件.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod] //这个属性 必不可少的
public static string GetServerTime() //静态的
{
return DateTime.Now.ToString();
}
}

总结ASP.NET AJAX在客户端JavaScript中异步调用服务器端Web Service,我们需要:

1 为Web Service类或需要暴露给客户端的Web Service方法添加[ScriptService]
属性;

2 为Web Service中需要暴露给客户端的方法添加[WebMethod]属性;

3 在页面中的ScriptManager控件中添加对该Web Service的引用;

4 在客户端使用如下JavaScript语法调用该Web Service:
[NameSpace].[ClassName].[MethodName](param1, param2,..., callbackFunction)

5 为客户端异步调用指定回调函数,在回调函数中接收返回值并进一步处理。

使用ASP.NET AJAX在客户端JavaScript中异步调用定义在ASP.NET页面中的方法,我们需要:

1 将该方法声明为公有(public);

2 将该方法声明为类方法(C#中的static,VB.NET中的Shared),而不是实例方法;

3 为该方法添加[WebMethod]属性;

4 将页面中ScriptManager控件的EnablePageMethods属性设置为true;

5 在客户端使用如下JavaScript语法调用该页面方法:
PageMethods.[MethodName](param1, param2,..., callbackFunction);

6 为客户端异步调用指定回调函数,在回调函数中接收返回值并进一步处理
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: