1)WebService端代码([System.Web.Script.Services.ScriptService]注释去掉)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
namespace WebApplication57
{
/// <summary>
/// WebService1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
/// <summary>
/// jquery ajax调用webservice传递简单参数
/// </summary>
/// <param name="SchoolID"></param>
/// <returns></returns>
[WebMethod]
public int Test1(int SchoolID, string SchoolName)
{
return SchoolID;
}
/// <summary>
/// jquery ajax调用webservice传递对象参数
/// </summary>
/// <param name="model"></param>
[WebMethod]
public School Test2(School model)
{
return model;
}
/// <summary>
/// jquery ajax调用webservice传递复杂参数
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[WebMethod]
public SchoolModel Test3(SchoolModel model)
{
return model;
}
}
public class SchoolModel : School
{
public List<Student> Students { get; set; }
}
public class School
{
public int SchoolID { get; set; }
public string SchoolName { get; set; }
}
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int SchoolID { get; set; }
}
}
2)前端代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication57.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
//jquery ajax调用webservice传递简单参数
var item1 = { SchoolID: 1, SchoolName: '嘉兴小学' };
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'WebService1.asmx/Test1',
data: JSON.stringify(item1),
dataType: 'json',
success: function (result) {
alert(result.d);
}
});
//jquery ajax调用webservice传递对象参数
var item2 = { model: { SchoolID: 1, SchoolName: '嘉兴小学' } };
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'WebService1.asmx/Test2',
data: JSON.stringify(item2),
dataType: 'json',
success: function (result) {
alert(result.d.SchoolName);
}
});
//jquery ajax调用webservice传递复杂参数
var item3 = {
model: {
SchoolID: 1,
SchoolName: '嘉兴小学',
Students: [
{ StudentID: 1, SchoolID: 1, StudentName: '张三' },
{ StudentID: 2, SchoolID: 1, StudentName: '李四' }]
}
};
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'WebService1.asmx/Test3',
data: JSON.stringify(item3),
dataType: 'json',
success: function (result) {
alert(result.d.Students.length);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>