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" "">
<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="问候" onclick="SayHello()" />
<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 = "")]
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}