在这篇文章中,我将说明什么在使用 Page Method 时什么是必要的以及什么是不必要的。然后我将展示在不使用 ScriptManager 时通过 jQuery 来调用 Page Method。
写一个 Page Method 是很简单的。 Page Method 必须声明为静态方法,并且它们必须使用 [WebMethod] 特性标注。除此之外,AJAX.NET AJAX 处理了其余在服务器需要做的工作。
下面是我们用于示例的 Page Method:
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
传统方法中,要使用 Page Method 的第一步就是设置 ScriptManager 的 EnablePageMethods 属性为 true。
幸运的是,这个属性名有一定程度上的用词不当。它并不会使 Page Method 可用,而仅仅是简单为页面代码中合适的方法生成了内嵌的 JavaScript 代理。
例如,如果在上面的示例对应的页面 Default.aspx 添加了一个 ScriptManager 并且设置了它的 EnablePageMethods 属性为 true,下面的 JavaScript 代码就会嵌入到页面中:
var PageMethods = function() {
PageMethods.initializeBase(this);
this._timeout = 0;
this._userContext = null;
this._succeeded = null;
this._failed = null;
}
PageMethods.prototype = {
_get_path:function() {
var p = this.get_path();
if (p) return p;
else return PageMethods._staticInstance.get_path();},
GetDate:function(succeededCallback, failedCallback, userContext) {
return this._invoke(this._get_path(), 'GetDate',false,{},
succeededCallback,failedCallback,userContext); }}
PageMethods.registerClass('PageMethods',Sys.Net.WebServiceProxy);
PageMethods._staticInstance = new PageMethods();
// Generic initialization code omitted for brevity.
PageMethods.set_path("/jQuery-Page-Method/Default.aspx");
PageMethods.GetDate = function(onSuccess,onFailed,userContext) {
PageMethods._staticInstance.GetDate(onSuccess,onFailed,userContext);
}
如果你不懂这段代码也没有关系,你不需要知道它是怎么工作的。你只需要知道这个 JavaScript 代理可以让你使用 PageMethods.MethodName 这样的语法来调用 Page Method。
这点重要的一点就是 PageMethods 代理对象归根结底就是一个规则 ASP.NET 服务调用的封装。
要知道调用 Page Method 与调用一个 Web 服务是一样的,使用 jQuery 调用 Page Method 并不难。要了解更详细的信息。
使用 jQuery 调用 Page Method,下面就是你所有需要做的:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
对应上面示例 Page Method 对应的 Default.aspx 如下:
<html>
<head>
<title>Calling a page method with jQuery</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="Default.js"></script>
</head>
<body>
<div id="Result">Click here for the time.</div>
</body>
</html>
正如你所看到的,这里没有 ScriptManager,更没有 EnablePageMethods。
下面是 Default.aspx 所引用的 Default.js:
$(document).ready(function() {
// 添加 Page Method 调用的函数作为 div 的 onclick 事件$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// 使用 Page Method 的返回值来替代 div 的内容
$("#Result").text(msg.d);
}
});
});
});
最后的结果就是当我们的 div 被点击之后,jQuery 发送一个 AJAX 请求到 GetDate Page Method 然后使用返回值替换 div 的内容。
Page Method 比一开始看起来更易于使用。EnablePageMethods 的相对不重要是一个惊喜。
为了避免使演示这个机制复杂,示例仅演示了最简单的目的。