JavaScript 非同步呼叫 PageMethod 之傳遞複雜資料類型

來源:互聯網
上載者:User

本節這個範例主要實現的是兩個知識點,

          一個就是使用 JavaScript 實現用戶端非同步呼叫 PageMethod ,

          二個就是使用 PageMethod 返回的是複雜資料類型 List 的泛型集合。

首先是實現 JavaScript 非同步呼叫 PageMethod ,

如同 JavaScript 非同步呼叫 WebService 一樣,必須先將 WebMethod 公開給 PageMethod,

必須注意的是,PageMethod 必須在 .aspx.cs 頁面中(不能是使用者控制項或者主版頁面中)實現,

然後就是 PageMethod 必須是採用 Public 修飾,並且是靜態 Static 修飾的方法,

既然是作為 WebService 的另外一種簡單實現,當然要加上 [WebMethod] 屬性標記,

這樣這個所謂的 PageMethod 便公開給了用戶端的 JavaScript 了。

然後便是一個複雜資料類型的傳遞問題,

也就是在伺服器端通過 WebService 或者 PageMethod ,

來傳遞一個複雜的資料類型給用戶端的 JavaScript 使用,

這其中主要涉及幾種稍微複雜的資料類型,比如傳遞一個類對象,

傳遞一個數組集合對象,更複雜的有泛型集合對象,

甚至是 DataTable(過於複雜,需要另行處理),

本次使用的是傳遞一個 List<Class T>泛型集合對象給 JavaScript ,

需要解釋的是,對於 List 傳遞到用戶端 JavaScript 中,其實也就是一個 Array 對象,

List<T> 的類型是 T ,那麼在 Array 中儲存的也是 T 對象,

所以只需要將服務端的 T 類型在用戶端使用同樣的替換類型,

就可以解決傳遞 List 泛型集合的問題了

直接看範例吧,

範例主要是通過在資料庫中擷取 "學生表" 中的"社會安全號碼碼"和"學生姓名",

然後將這兩個欄位動態綁定到“下拉式清單方塊”控制項上,

然後使用者在下拉式清單方塊中選擇一個學生,然後單擊一個用戶端的按鈕,

通過這個按鈕執行 JavaScript  來訪問 PageMethod ,

再在 PageMethod 中得到這個學生所有的資料後,

採用返回一個 List<T> 對象到用戶端。

.aspx.cs

public partial class Demo__6 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}

private void BindData()
{
    string conStr = WebConfigurationManager.

                    ConnectionStrings["Demo"].ConnectionString;
    string sqlStr = "SELECT 學生姓名,社會安全號碼碼 FROM 學生";
    DataSet myDataSet = new DataSet();

    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(myDataSet);
            }
        }
    }
    ddlStudent.DataSource = myDataSet.Tables[0];
    ddlStudent.DataTextField = "學生姓名";
    ddlStudent.DataValueField = "社會安全號碼碼";
    ddlStudent.DataBind();
}

[WebMethod]
public static List<Demo__6__Use> MyPageMethodList(string id)
{
    List<Demo__6__Use> myList = new List<Demo__6__Use>();

    string conStr = WebConfigurationManager.
                    ConnectionStrings["Demo"].ConnectionString;
    string sqlStr = "SELECT * FROM 學生 WHERE 社會安全號碼碼=@ID";
    using (SqlConnection sqlCon = new SqlConnection(conStr))
    {
        sqlCon.Open();
        using (SqlCommand sqlCom = sqlCon.CreateCommand())
        {
            sqlCom.CommandText = sqlStr;
            sqlCom.CommandType = CommandType.Text;
            sqlCom.Parameters.AddWithValue("@ID", id);
            using (SqlDataReader sqlDr = sqlCom.ExecuteReader())
            {
                if (sqlDr.Read())
                {

                    //這裡如此多的 Try-Catch 是防止 sqlDr.GetBoolean(2).ToString())

                    //資料為空白,如果不設定 Try-Catch 塊,則資料為空白時,

                    //則會拋出異常,導致非同步呼叫失敗,在用戶端則會執行 OnFailed 錯誤處理函數
                    try
                    {
                        myList.Add(new Demo__6__Use("學生姓名",
                               sqlDr.GetSqlString(1).Value));

                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("學生姓名", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("性別",
                               sqlDr.GetBoolean(2).ToString()));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("性別", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("家長姓名",
                               sqlDr.GetSqlString(3).Value));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("家長姓名", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("家庭地址",
                               sqlDr.GetSqlString(4).Value));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("家長地址", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("郵遞區號",
                               sqlDr.GetSqlString(5).Value));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("郵遞區號", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("電話號碼",
                               sqlDr.GetSqlString(6).Value));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("電話號碼", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("出生日期",
                               sqlDr.GetDateTime(7).ToString()));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("出生日期", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("身高",
                               sqlDr.GetValue(8).ToString()));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("身高", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("體重",
                               sqlDr.GetValue(9).ToString()));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("體重", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("血型",
                               sqlDr.GetSqlString(10).Value));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("血型", "空資料"));
                    }
                    try
                    {
                        myList.Add(new Demo__6__Use("簡歷",
                               sqlDr.GetSqlString(11).Value));
                    }
                    catch
                    {
                        myList.Add(new Demo__6__Use("簡歷", "空資料"));
                    }
                }
            }
        }
    }
    return myList;
}

Demo__6__Use.cs 這個類

public class Demo__6__Use
{
    private string dictionaryKey;

    public string DictionaryKey
    {
        get { return dictionaryKey; }
        set { dictionaryKey = value; }
    }
    private string dictionaryvalue;

    public string DictionaryValue
    {
        get { return dictionaryvalue; }
        set { dictionaryvalue = value; }
    }

    public Demo__6__Use(string key, string value)
    {
        this.DictionaryKey = key;
        this.DictionaryValue = value;
    }
}

. aspx 頁面 HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script language="javascript" type="text/javascript">

        function btnSearch_onclick() {
            var ddlStudent = $get('<%=ddlStudent.ClientID %>');
            PageMethods.MyPageMethodList(
                        ddlStudent[ddlStudent.selectedIndex].value,
                        OnSucceeded, OnFailed);

        }

        function OnSucceeded(result) {
            var msg = "";
            var studentName = new Object();
            studentName.DictionaryKey = result[0].DictionaryKey;
            studentName.DictionaryValue = result[0].DictionaryValue;

            msg += studentName.DictionaryKey + "         " +
                   studentName.DictionaryValue + "\n";

            var sex = new Object();
            sex.DictionaryKey = result[1].DictionaryKey;
            sex.DictionaryValue = result[1].DictionaryValue;
            msg += sex.DictionaryKey + "         " +
                   sex.DictionaryValue + "\n";

            var fatherName = new Object();
            fatherName.DictionaryKey = result[2].DictionaryKey;
            fatherName.DictionaryValue = result[2].DictionaryValue;
            msg += fatherName.DictionaryKey + "        " +
                   fatherName.DictionaryValue + "\n";

            var address = new Object();
            address.DictionaryKey = result[3].DictionaryKey;
            address.DictionaryValue = result[3].DictionaryValue;
            msg += address.DictionaryKey + "        " +
                   address.DictionaryValue + "\n";

            var postCode = new Object();
            postCode.DictionaryKey = result[4].DictionaryKey;
            postCode.DictionaryValue = result[4].DictionaryValue;
            msg += postCode.DictionaryKey + "        " +
                   postCode.DictionaryValue + "\n";

            var phoneNumber = new Object();
            phoneNumber.DictionaryKey = result[5].DictionaryKey;
            phoneNumber.DictionaryValue = result[5].DictionaryValue;
            msg += phoneNumber.DictionaryKey + "        " +
                   phoneNumber.DictionaryValue + "\n";

            var birthDate = new Object();
            birthDate.DictionaryKey = result[6].DictionaryKey;
            birthDate.DictionaryValue = result[6].DictionaryValue;
            msg += birthDate.DictionaryKey + "        " +
                   birthDate.DictionaryValue + "\n";

            var height = new Object();
            height.DictionaryKey = result[7].DictionaryKey;
            height.DictionaryValue = result[7].DictionaryValue;
            msg += height.DictionaryKey + "        " +
                   height.DictionaryValue + "\n";

            var weight = new Object();
            weight.DictionaryKey = result[8].DictionaryKey;
            weight.DictionaryValue = result[8].DictionaryValue;
            msg += weight.DictionaryKey + "        " +
                   weight.DictionaryValue + "\n";

            var bloodType = new Object();
            bloodType.DictionaryKey = result[9].DictionaryKey;
            bloodType.DictionaryValue = result[9].DictionaryValue;
            msg += bloodType.DictionaryKey + "        " +
                   bloodType.DictionaryValue + "\n";

            var studentMsg = new Object();
            studentMsg.DictionaryKey = result[10].DictionaryKey;
            studentMsg.DictionaryValue = result[10].DictionaryValue;
            msg += studentMsg.DictionaryKey + "        " +
                   studentMsg.DictionaryValue + "\n";

            var lblMsg = $get('<%=lblMsg.ClientID %>');
            lblMsg.innerText = msg;
        }

        function OnFailed(error) {
            var msg = "錯誤資訊" + error.get_message();
            alert(msg);
        }
 
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <div>
        選擇學生&nbsp;&nbsp;
        <asp:DropDownList ID="ddlStudent" runat="server" Width="150px">
        </asp:DropDownList>
        &nbsp;&nbsp;
        <input id="btnSearch" type="button" value="&gt;&gt;"
               onclick="return btnSearch_onclick()" /><br />
        <br />
        <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
        <br />
        <br />
    </div>
    </form>
</body>
</html>

以上就是這個範例的一個基本實現,需要注意的幾點在博文前面都講的很清楚了,

不清楚的可以直接看代碼,代碼寫的很簡單,只要注意我標記的地方就 OK 了

結果

 

 

                                                                   2010—1—26

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.