asp.net ajax项目调用webservice
一、新建网站、asp.net ajax项目
web.config文件以自动生成、项目引用以自动完成
二、新建aspx页面,如下代码
三、新建webservice文件,如下代码
其中,给aspx托一个ScriptManager,在ScriptManager的Services中指定WebService文件;指定Scripts的Assembly和Name
四、运行
<%@ 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>无标题页</title>
<link href="../Css/StyleSheet.css" rel="stylesheet" type="text/css" />
<script type="text/jscript">
var g_tbName = null;
var g_btnSayHello = null;
var g_lbMessage = null;
function pageLoad()
{
g_tbName = new Sys.Preview.UI.TextBox($get('tbName'));
g_tbName.initialize();
g_btnSayHello = new Sys.Preview.UI.Button($get('btnSayHello'));
g_btnSayHello.add_click(getServerHelloString);
g_btnSayHello.initialize();
g_lbMessage = new Sys.Preview.UI.Label($get('lbMessage'));
g_lbMessage.initialize();
}
function getServerHelloString()
{
HelloWorldService.GetHelloWorldString(g_tbName.get_text(),cb_getServerHelloString);
}
function cb_getServerHelloString(result)
{
g_lbMessage.set_text(result);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<label for="tbName">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="HelloWorldService.asmx" />
</Services>
<Scripts>
<asp:ScriptReference Assembly="Microsoft.Web.Preview" Name="PreviewScript.js" />
</Scripts>
</asp:ScriptManager>
<br />
Your Name:</label><input id="tbName" type="text" />
<input id="btnSayHello" type="button" value="Say Hello From Server!" />
<div id="lbMessage">
</div>
<div>
</div>
</form>
</body>
</html>
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
/// <summary>
/// WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]//让ASP.NET AJAX能够从客户端访问到该Web Service所必需的
public class HelloWorldService : System.Web.Services.WebService {
public HelloWorldService()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string GetHelloWorldString(string name)
{
//return "Hello World";
return string.Format("Welcome to ASP.NET AJAX world, {0}!. Now it is {1}.", name,DateTime.Now);
}
}