客户端 JavaScript 调用 ASP.NET WebService 的方法除了采用 WebServer.htc 和 构造 SOAPAction 的方法外,下面介绍一个采用 Ajax 调用的简单方法,并且可以传递参数。其实,ASP.NET WebService 就是一个网站,所以,Request 对象是可用的,这样,传递参数就很容易了。下面是一个WebService1.asmx的代码
ASMX 代码
<%@ WebService Language="C#" CodeBehind="WebService1.asmx.cs" Class="WebService1" %>
C# 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
// 字符串返回测试
public string GetServerTime()
{
return "当前服务器时间:" + DateTime.Now.ToString();
}
[WebMethod]
// long 类型返回测试
public long GetServerTimeTicks()
{
return DateTime.Now.Ticks;
}
[WebMethod]
// Datatable返回测试
public DataTable GetTestDataTable()
{
DataTable dt = new DataTable("TestTable");
DataRow dr;
dt.Columns.Add(new DataColumn("id", typeof(Int32)));
dt.Columns.Add(new DataColumn("text", typeof(string)));
for (int i = 0; i < 6; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "列表项目 " + i.ToString();
dt.Rows.Add(dr);
}
return dt;
}
[WebMethod]
// List 类型测试
public List<User> GetTestUser()
{
//传递参数传测试
string param = this.Context.Request.QueryString["param"];
if (param == null) param= this.Context.Request.Form["param1"];
List<User> u_list = new List<User>();
for (int i = 0; i < 10; i++)
{
User u = new User();
u.Name = "LoginName" + i.ToString() + " param = " + param;
u.Title = "孟宪会" + i.ToString();
u_list.Add(u);
}
return u_list;
}
//定义一个对象 User
public class User
{
public String Name { get; set; }
public String Title { get; set; }
}
}