JavaScript 非同步呼叫 WCF 服務 & 傳遞複雜類型

來源:互聯網
上載者:User

在前面的幾篇博文中,

對 JavaScript 使用 WebService 和使用 PageMethod 均有了比較詳細的介紹,

而在接下來的幾篇博文中呢,

則主要是介紹一下在 ASP.NET AJAX 中如何使用 WCF 服務,

並且會介紹一些簡單的但需要注意的地方,

在這裡還是採取直接使用 Demo 進行解釋的方式來介紹,

一開始,還是對下面的這個 Demo 進行簡要的介紹吧,

首先,這個 Demo 呢,

是通過使用者在前端的下拉式清單方塊中選擇一個學生,

然後再通過 JavaScript 非同步呼叫 WCF 服務來完成其他的任務,

WCF 服務中的功能則是使用傳遞過來的參數--學生社會安全號碼碼,

使用這個參數完成在資料庫中查詢出這名學生的所有資訊,

然後會分別以 List<string> 和 Dictionary<string,string>

兩種方式將查詢到的學生資訊返回給 JavaScript 處理。

該 Demo 的注重點有兩個,

一個呢,就是學會如何通過 JavaScript 調用 WCF 服務,

二個呢,就是學會如何在用戶端處理由服務端傳遞來的稍微複雜的資料類型,

接下來就是看 Demo 了,

在看樣本之前,還是先介紹一下項目的建立吧,

首先是建立一個 .aspx 頁面,然後是要建立一個 .svc 的 WCF 服務,

在此建立時,您最好是選擇 “啟用了 AJAX 的 WCF 服務”,

因為,要使 JavaScript 可以訪問 WCF 服務,

必須在 web.config 中進行一些配置,

而如果您選擇 “啟用了 AJAX 的 WCF 服務”的話,

那麼這些在 web.config 中的配置會自動完成,而無需我們過多幹預,

當然,對於 web.config 中的一些配置,在下一篇博文中會有所介紹,

然後您便可以在這個 .svc.cs 中鍵入伺服器端代碼,

然後就可以在 .aspx 中通過 JavaScript 使用這個服務了

(其中的一些細節下一篇博文再介紹)

接下來就看 Demo 了

先看 .svc 吧

<%@ ServiceHost Language="C#" Debug="true"
    Service="深入淺出_ASP.NET_AJAX.WCFDemo21Use"
    CodeBehind="WCFDemo21Use.svc.cs" %>

再來看一下 .svc.cs 吧

using System.ServiceModel;
using System.ServiceModel.Activation;

using System.Data.SqlClient;
using System.Web.Configuration;
using System.Collections.Generic;

namespace 深入淺出_ASP.NET_AJAX
{
    //要使用戶端 JavaScript 可以訪問這個 WCF
    //則必須通過標記 ServiceContractAttribute 來對 JavaScript 公開這個 WCF
    //同時在這裡可以定義這個 WCF 所屬的命名空間
    //如果指定了命名空間,那麼在用戶端產生 JavaScript Proxy 時
    //也要有這個命名空間的首碼
    [ServiceContract(Namespace = "BaoBeiMe")]
    [AspNetCompatibilityRequirements(RequirementsMode =
        AspNetCompatibilityRequirementsMode.Allowed)]
    public class WCFDemo21Use
    {
        private string conStr = WebConfigurationManager.
             ConnectionStrings["Demo"].ConnectionString;

        // 添加 [WebGet] 屬性以使用 HTTP GET
       [OperationContract]
       //使用 Dictionary<string,string> 泛型集合完成
        public Dictionary<string, string> GetDictionaryStudentMsg(string id)
        {
            //定義一個字典對象
            Dictionary<string, string> studentDic = new Dictionary<string, string>();

            string sqlStr = "SELECT 社會安全號碼碼,學生姓名,性別," +
                            "家長姓名,家庭地址,郵遞區號,電話號碼," +
                            "出生日期 FROM 學生 WHERE 社會安全號碼碼=@ID";

            using (SqlConnection sqlCon = new SqlConnection(conStr))
            {
                sqlCon.Open();
                using (SqlCommand sqlCom = sqlCon.CreateCommand())
                {
                    sqlCom.CommandText = sqlStr;
                    sqlCom.Parameters.AddWithValue("@ID", id);
                    using (SqlDataReader sqlDr = sqlCom.ExecuteReader())
                    {
                        if (sqlDr.Read())
                        {
                            studentDic["社會安全號碼碼"] = sqlDr.GetSqlString(0).Value;
                            studentDic["學生姓名"] = sqlDr.GetSqlString(1).Value;
                            studentDic["性別"] = sqlDr.GetBoolean(2).ToString();
                            studentDic["家長姓名"] = sqlDr.GetSqlString(3).Value;
                            studentDic["家庭地址"] = sqlDr.GetSqlString(4).Value;
                            studentDic["郵遞區號"] = sqlDr.GetSqlString(5).Value;
                            studentDic["電話號碼"] = sqlDr.GetSqlString(6).Value;
                    studentDic["出生日期"] = sqlDr.GetDateTime(7).ToShortDateString();
                        }
                    }
                }
            }
            return studentDic;
        }

        //使用 List <string> 泛型集合完成
       [OperationContract]
        public List<string> GetListStudentMsg(string id)
        {
           //定義一個泛型集合對象
            List<string> studentList = new List<string>();
            string sqlStr = "SELECT 社會安全號碼碼,學生姓名,性別," +
                            "家長姓名,家庭地址,郵遞區號,電話號碼," +
                            "出生日期 FROM 學生 WHERE 社會安全號碼碼=@ID";

            using (SqlConnection sqlCon = new SqlConnection(conStr))
            {
                sqlCon.Open();
                using (SqlCommand sqlCom = sqlCon.CreateCommand())
                {
                    sqlCom.CommandText = sqlStr;
                    sqlCom.Parameters.AddWithValue("@ID", id);
                    using (SqlDataReader sqlDr = sqlCom.ExecuteReader())
                    {
                        if (sqlDr.Read())
                        {
                            studentList.Add(sqlDr.GetSqlString(0).Value);
                            studentList.Add(sqlDr.GetSqlString(1).Value);
                            studentList.Add(sqlDr.GetBoolean(2).ToString());
                            studentList.Add(sqlDr.GetSqlString(3).Value);
                            studentList.Add(sqlDr.GetSqlString(4).Value);
                            studentList.Add(sqlDr.GetSqlString(5).Value);
                            studentList.Add(sqlDr.GetSqlString(6).Value);
                            studentList.Add(sqlDr.GetDateTime(7).ToShortDateString());
                        }
                    }
                }
            }
            return studentList;
        }
    }
}

再來看一下 .aspx.cs 吧

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace 深入淺出_ASP.NET_AJAX
{
    public partial class Demo__21 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataSet ds = new DataSet();
                string conStr = ConfigurationManager.
                     ConnectionStrings["Demo"].ConnectionString;
                string sqlStr = "SELECT 社會安全號碼碼,學生姓名 FROM 學生";
                using (SqlConnection sqlCon = new SqlConnection(conStr))
                {
                    using (SqlCommand sqlCom = sqlCon.CreateCommand())
                    {
                        sqlCom.CommandType = CommandType.Text;
                        sqlCom.CommandText = sqlStr;
                        using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCom))
                        {                          
                            sqlDa.Fill(ds);
                        }
                    }
                }
                ddlStudent.DataSource = ds.Tables[0].DefaultView;
                ddlStudent.DataTextField = "學生姓名";
                ddlStudent.DataValueField = "社會安全號碼碼";
                ddlStudent.DataBind();
            }
        }
    }
}

再來看一下 .aspx 中的 HTML

<%@ Page Language="C#" AutoEventWireup="true"
    CodeBehind="Demo__21.aspx.cs"
    Inherits="深入淺出_ASP.NET_AJAX.Demo__21" %>

<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="~/WCFDemo21Use.svc"/>
        </Services>
    </asp:ScriptManager>

    <script language="javascript" type="text/javascript">
        function btnQueryDictionary_onclick() {
            //擷取頁面上的 DropDownList
            var ddlStudent = $get('<%=ddlStudent.ClientID %>');
            //得到這個下拉式清單方塊選擇的項的 Value
            var studentID = ddlStudent.options[ddlStudent.selectedIndex].value;
            //WCF 和 WebService 一樣,也是通過在用戶端產生 JavaScript Proxy 類,
            //再通過這個類來完成和伺服器的互動的
            //在這裡就是要執行個體化一個 WCF 服務在用戶端的代理類
           var wcfProxy = new BaoBeiMe.WCFDemo21Use();
           //通過用戶端代理類便可以調用 WCF 中的方法了
            wcfProxy.GetDictionaryStudentMsg(studentID,
                          OnSucceededCallback, OnFailedCallback);
        }

        function btnQueryList_onclick() {
            //擷取頁面上的 DropDownList
            var ddlStudent = $get('<%=ddlStudent.ClientID %>');
            //得到這個下拉式清單方塊選擇的項的 Value
            var studentID = ddlStudent.options[ddlStudent.selectedIndex].value;
            //WCF 和 WebService 一樣,也是通過在用戶端產生 JavaScript Proxy 類,
            //再通過這個類來完成和伺服器的互動的
            //在這裡就是要執行個體化一個 WCF 服務在用戶端的代理類
            var wcfProxy = new BaoBeiMe.WCFDemo21Use();
            //通過用戶端代理類便可以調用 WCF 中的方法了
            wcfProxy.GetListStudentMsg(studentID,
                          OnSucceededCallback, OnFailedCallback);
        }

        function OnSucceededCallback(result, userContext, methodName) {
            if (methodName == "GetDictionaryStudentMsg") {
                var msg = "這個是通過返回一個 Dictionary<string,string> 來完成的\n";
                //由於服務端會返回一個 Dictionary 的字典,所以會有 Value 和 Key 值
                //注意訪問方式
                for (var key in result) {
                    msg += result[key].Key + ": " + result[key].Value + "\n";
                }
                $get('<%=lblMsg.ClientID%>').innerText = msg;

            }
            if (methodName == "GetListStudentMsg") {
               //服務端返回的是一個 List 的集合對象
                //這個集合在用戶端會被解析為一個 Array 對象
                var arrayList = new Array();
                arrayList = result;
                var msg = "這個是通過返回一個 List<string> 來完成的\n";
                msg += "社會安全號碼碼: " + arrayList[0] + "\n";
                msg += "學生姓名: " + arrayList[1] + "\n";
                msg += "性別: " + arrayList[2] + "\n";
                msg += "家長姓名: " + arrayList[3] + "\n";
                msg += "家庭地址: " + arrayList[4] + "\n";
                msg += "郵遞區號: " + arrayList[5] + "\n";
                msg += "電話號碼: " + arrayList[6] + "\n";
                msg += "出生日期: " + arrayList[7] + "\n";
                $get('<%=lblMsg.ClientID%>').innerText = msg;
            }
        }

        function OnFailedCallback(error, userContext, methodName) {
            alert("異常資訊:" + error.get_message() + "\n" +
                  "異常類型:" + error.get_exceptionType() + "\n" +
                  "堆棧資訊:" + error.get_stackTrace());
        }
    </script>

    <div>
        <asp:DropDownList ID="ddlStudent" runat="server" Width="200">
        </asp:DropDownList>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <br />
        <br />
        <input id="btnQueryDictionary" type="button"
            value="查看學生資訊--通過Dictionary"
            onclick="return btnQueryDictionary_onclick()" /><br />
        <br />
        <input id="btnQueryList" type="button"
            value="查看學生資訊--通過List"
            onclick="return btnQueryList_onclick()" /></div>
    <div>
        <br />
        <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

看一下結果吧

以上就是整個的一個 Demo 了,

其實呢,對於 WCF 的配置還是比較複雜的,

只不過,我們使用了 “啟用了 AJAX 的 WCF 服務”這個功能塊,

所以對於 web.config 的所有的配置都有 VS 自動給完成了,

所以幫我們節省了很多的時間和精力。

這篇博文呢,說實在的,只是一個示範如何使用 JavaScript 來訪問 WCF ,

而對其中的一些細節全部都進行了忽略,也沒有進行說明,

不過,在以下博文中便會細說的。

                                                      2010—2—03

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.