PageMethods(WebService) 處理 class 型別

  • 2698
  • 0

PageMethods(WebService) 處理 class 型別

在書上看到這東東的應用..發現還蠻不錯的..就測試一下..看原始碼說故事摟..^^..

.aspx網頁上就丟兩個button..

<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>
    <div>
        <input type="button" value="test" onclick="getMsgC();" />
        <input type="button" value="post" onclick="setMsgC();" />
    </div>
    </form>
</body>
 
.aspx再把下面的js丟上去..就是去寫PageMethod
 
<script type="text/javascript">
//抓取server端的class-------------------------------
function getMsgC()
{
    PageMethods.getClass(5,4,3,getFinall);
}
function getFinall(result)
{
    alert(result.a + ',' + result.b + ',' + result.c);
}

//設定server端的class,然後在取回class-------------------------------
function setMsgC()
{
    var method = new setMsg();
    method.a = 999;
    method.b = 999;
    method.c = 999;
    
    PageMethods.setMehod(method,setFinall);
}
function setFinall(result)
{
    alert(result.a + ',' + result.b + ',' + result.c);
}
</script>
 
.cs 這裡就放該放的原始碼..
 
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Script.Services;
using System.Web.Services;

public partial class test_json : System.Web.UI.Page
{
    //抓取server端的class
    [WebMethod]
    public static getMsg getClass(int msg1, int msg2, int msg3)
    {
        return new getMsg() { a = msg1, b = msg2, c = msg3 };
    }

    //設定server端的class
    [WebMethod]
    [GenerateScriptType(typeof(setMsg))]
    [ScriptMethod(UseHttpGet = true)]
    public static setMsg setMehod(setMsg obj)
    {
        return obj;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
}
public class getMsg
{
    public getMsg() { }

    public int a { get; set; }
    public int b { get; set; }
    public int c { get; set; }
}

public class setMsg
{
    public setMsg() { }

    public int a { get; set; }
    public int b { get; set; }
    public int c { get; set; }
}
 

上面這原始碼的意思是說..用PageMethod來傳遞設定class..微軟在應用PageMethod(WebService)
這些方法會是用json格式來傳遞資料,我們接到server端傳回來的東西後..就會經過Sys.Serialization.JavaScriptSerializer
來處理它..之後就會丟到我們設定的回呼函式..這樣就可以收到結果啦..Rolling on the floor..真是個蠻方便的東東..
ADO.NET Data Services印象中也有提供一組專屬的js來做同樣的事情..沒用力去研究..
有錯要提醒一下ㄟ..

參考:
asp.net ajax in action
http://www.asp.net/AJAX/Documentation/Live/ClientReference/default.aspx