ASP.Net AJax跟atlas有了很大不同。從這個簡單的例子中可以看出幾點。
<1>新建一個ASP.Net AJax-enabled web site
<2>頁面布局。Server Controls的標簽前綴(Tag Prefix)由atlas變為ASP;
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.ASPx.cs" Inherits="HelloWorld" %>
<!DOCTYPE Html PUBLIC "-//W3C//DTD XHtml 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xHtml11.dtd">
<Html>
<head runat="server">
<title>Hello</title>
</head>
<body>
<form id="form1" runat="server">
<ASP:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<ASP:ServiceReference Path="~/HelloWorldService.asmx" />
</Services>
</ASP:ScriptManager>
<div>
你的名字:
<input type="text" maxlength="20" id="name" />
<input type="button" id="button1" value="問候" />
<div id="result"></div>
</div>
</form>
</body>
</Html><3>客戶端腳本。調用服務的方法有些許改變。可以指定默認的回調方法。
<script type="text/Javascript">
function SayHello()
{
var fs = HelloWorldService;
fs.set_defaultSucceededCallback(OnShow);
fs.HelloWorld(document.getElementById("name").value);
}
function OnShow(result)
{
var s = document.getElementById("result");
s.innerText = result;
}
</script>
<4>HelloWorldService服務代碼。為了能使服務被ASP.Net AJax客戶端調用,必須給服務指明[ScriptService]屬性(為了使用這一屬性,需要引用Microsoft.Web.Script.Services命名空間)。
1using System;
2using System.Web.Services;
3using System.Web.Services.Protocols;
4using Microsoft.Web.Script.Services;
5
6[WebService(Namespace = "http://tempuri.org/")]
7[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
8[ScriptService]
9public class HelloWorldService : System.Web.Services.WebService {
10
11 public HelloWorldService () {
12
13 //Uncomment the following line if using designed components
14 //InitializeComponent();
15 }
16
17 [WebMethod]
18 public string HelloWorld(string name) {
19 string hello = String.IsNullOrEmpty(name) ? "無名氏" : name;
20 hello += "你好,當前服務器時間是:";
21 hello += DateTime.Now.ToUniversalTime();
22 return hello;
23 }
24
25}