Asp.Net Ajax 如何调用WebService

利用Asp.Net自带的Ajax调用WebService 中的方法非常方便,甚至不需要任何Javascript代码,主要是下面的第4步里,如何调用WebService

<asp:ScriptManager ID="ScriptManager1" runat="server">

    <Services>

        <asp:ServiceReference Path="路径/方法名1" />

         <asp:ServiceReference Path="路径/方法名2" />

    </Services>

</asp:ScriptManager>

 

1、建立项目WebServiceWebApp项目,如图所示,(我这里用了英文版,最近发现如果用汉语版的话,会出现些问题:1、添加不了Dynamic Data WebApplication,一添加就出错。2、如果把返回为一个集合的存储过程拖放到Linq To SQL Class时,如果不指定返回值,生成的方法名后夹杂些汉语)

2Service1.asmx代码为:(这部分其实和上篇的代码是一样的)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Data;

 

namespace WebService1

{

    /// <summary>

    /// Summary description for Service1

    /// </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 Service1 : System.Web.Services.WebService

    {

 

        //无参方法

        [WebMethod]

        public string HelloWorld()

        {

            return "Hello World";

        }

 

        //有参方法1

        [WebMethod]

        public int Add(int a, int b)

        {

            return a + b;

        }

 

        //有参方法2

        [WebMethod]

        public int Sum(int x)

        {

            int sum = 0;

            for (int i = 0; i <= x; i++)

            {

                sum += i;

            }

            return sum;

        }

 

        // 返回一个复合类型

        [WebMethod]

        public Student GetStudentByStuNo(string stuNo)

        {

            if (stuNo == "001")

                return new Student { StuNo = "001", StuName = "张三" };

            if (stuNo == "002")

                return new Student { StuNo = "002", StuName = "李四" };

            return null;

        }

 

        //返回返回泛型集合的

        [WebMethod]

        public List<Student> GetList()

        {

            List<Student> list = new List<Student>();

            list.Add(new Student() { StuNo = "001", StuName = "张三" });

            list.Add(new Student() { StuNo = "002", StuName = "李四" });

            list.Add(new Student() { StuNo = "003", StuName = "王五" });

            return list;

        }

 

        //返回DataSet

        [WebMethod]

        public DataSet GetDataSet()

        {

            DataSet ds = new DataSet();

            DataTable dt = new DataTable();

            dt.Columns.Add("StuNo", Type.GetType("System.String"));

            dt.Columns.Add("StuName", Type.GetType("System.String"));

            DataRow dr = dt.NewRow();

            dr["StuNo"] = "001"; dr["StuName"] = "张三";

            dt.Rows.Add(dr);

 

            dr = dt.NewRow();

            dr["StuNo"] = "002"; dr["StuName"] = "李四";

            dt.Rows.Add(dr);

 

            ds.Tables.Add(dt);

 

            return ds;

        }

 

    }

 

    public class Student

    {

        public string StuNo { get; set; }

        public string StuName { get; set; }

    }

}

 

3、打开WebApp项目AjaxInvokeWebService里的web.config文件,在system.web节下面加上以下配置

    <webServices >

        <protocols >

            <add name="HttpSoap"/>

            <add name="HttpPost"/>

            <add name="HttpGet"/>

            <add name="Documentation"/>

        </protocols>

    </webServices>

4Default.aspx代码如下,这部分需要注意,ScriptManager必需紧跟放在form之后,<Services></Services>中的<asp:ServiceReference Path="" />用来调用WebService。一个WebService方法对应一个<asp:ServiceReference Path="" />

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AjaxInvokeWebService._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server">

        <Services>

            <asp:ServiceReference Path="http://localhost:1832/Service1.asmx/HelloWorld" />

            <asp:ServiceReference Path="http://localhost:1832/Service1.asmx/Add" />

            <asp:ServiceReference Path="http://localhost:1832/Service1.asmx/GetStudentByStuNo" />

            <asp:ServiceReference Path="http://localhost:1832/Service1.asmx/GetList" />

            <asp:ServiceReference Path="http://localhost:1832/Service1.asmx/GetDataSet" />

        </Services>

    </asp:ScriptManager>

    <div>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">

            <ContentTemplate>

                <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="调用无参方法" />

                &nbsp;<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="调用有参方法" />

                &nbsp;<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="调用复合类型" />

                &nbsp;<asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="调用泛型集合" />

                &nbsp;<asp:Button ID="Button5" runat="server" OnClick="Button5_Click" Text="调用DataSet类型" />

                <br />

                <asp:Label ID="lblResult" runat="server"></asp:Label>

                <asp:GridView ID="GridView1" runat="server">

                </asp:GridView>

            </ContentTemplate>

        </asp:UpdatePanel>

    </div>

    </form>

</body>

</html>

5Default.aspx.cs代码如下

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

namespace AjaxInvokeWebService

{

    public partial class _Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protected void Button1_Click(object sender, EventArgs e)

        {

            //调用无参方法

            lblResult.Text =new localhost.Service1().HelloWorld();

        }

 

        protected void Button2_Click(object sender, EventArgs e)

        {

            //调用有参方法

            lblResult.Text = new localhost.Service1().Add(2, 3).ToString();

        }

 

        protected void Button3_Click(object sender, EventArgs e)

        {

            //调用复合类型

            localhost.Student s = new localhost.Student();

            s = new localhost.Service1().GetStudentByStuNo("001");

            lblResult.Text = "学号="+s.StuNo + ",姓名=" + s.StuName;

        }

 

        protected void Button4_Click(object sender, EventArgs e)

        {

            //调用泛型集合

            GridView1.DataSource = new localhost.Service1().GetList();

            GridView1.DataBind();

        }

 

        protected void Button5_Click(object sender, EventArgs e)

        {

            //调用DataSet类型

            GridView1.DataSource = new localhost.Service1().GetDataSet();

            GridView1.DataBind();

        }

    }

}

 

运行效果为

 

 

参考:

http://blog.163.com/figo_2007@126/blog/static/231807652009324959694/

http://wind721888.blog.163.com/blog/static/31574639201051355844676/?fromdm&fromSearch&isFromSearchEngine=yes

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值