[memo] JQuery PageMethod (續)
繼上一篇簡單記錄如何使用JQuery呼叫PageMethod來開發後,再次筆記一下使用重點。
其實多數使用這種開發方式的工程師,大都會採取撰寫ashx…
不過使用PageMethod其實也有其便利的地方,當你搭配良好的開發架構,其實也不一定要撰寫ashx啦。
(好吧~其實是自己偷懶orz~~)
上次沒有筆記到怎麼從頁面上帶參數給後端,這次就順便筆記一下。
步驟一:
首先我們得準備一下Client Script 如下:
1: var PersonDto = function () {
2: this.Name = '',
3: this.Age = ''
4: }
5:
6: PersonDto.prototype = function () {
7: SayHello: function () {
8: alert('Hello');
9: }
10: }
步驟二:
撰寫C# 對應的Class 如下:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5:
6: /// <summary>
7: /// PersonDto 的摘要描述
8: /// </summary>
9: public class PersonDto
10: {
11: public string Name { get; set; }
12: public string Age { get; set; }
13: }
步驟三:
在code behind 撰寫要被呼叫的Method
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Web;
5: using System.Web.UI;
6: using System.Web.UI.WebControls;
7: using System.Web.Services;
8:
9: public partial class PageMethod2 : System.Web.UI.Page
10: {
11: protected void Page_Load(object sender, EventArgs e)
12: {
13:
14: }
15:
16: [WebMethod(EnableSession = true)]
17: public static PersonDto SayHello(PersonDto data)
18: {
19: PersonDto person = new PersonDto();
20: person.Name = "陳大胖";
21: person.Age = "30";
22: return person;
23: }
24: }
步驟四:
撰寫大量 JQuery Code
1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageMethod2.aspx.cs" Inherits="PageMethod2" %>
2:
3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4: <html xmlns="http://www.w3.org/1999/xhtml">
5: <head runat="server">
6: <script src="Scripts/jquery-1.5.2.min.js" type="text/javascript"></script>
7: <script src="Scripts/PageDto.js" type="text/javascript"></script>
8: <script src="Scripts/jquery.json-2.3.min.js" type="text/javascript"></script>
9: <script type="text/javascript">
10: function Submit() {
11: var person = new PersonDto();
12: person.Name = $('#txtName').val();
13: var data = "{data:" + $.toJSON(person) + "}";
14: $.ajax({
15: type: "post",
16: url: "PageMethod2.aspx/SayHello",
17: data: data,
18: dataType: 'json',
19: contentType: 'application/json; charset=utf-8',
20: success: function (data) {
21: var response = data.d;
22: alert(response.Name);
23: }
24: });
25: }
26: </script>
27: <title>PageMethod應用二</title>
28: </head>
29: <body>
30: <div>
31: 姓名:
32: <input id="txtName" type="text" />
33: <button id="" onclick="Submit()">
34: 送出</button>
35: </div>
36: <div id="divResult">
37: </div>
38: </body>
39: </html>
大體上就是上述四個步驟,結果我就不貼了,這樣開發方式大概只省了從client post object 與 server 自訂類別對應的code