在 ASP.NET AJAX 開發中,PageMethods 是呼叫後端靜態方法的常用機制。當出現「未定義」或「物件不支援此屬性或方法」錯誤時,請依序排查以下 5 大關鍵點:
<system.web> 區段包含 <pages> 控制項註冊,且 <httpHandlers>、<httpModules> 正確配置 ScriptModule。<asp:ScriptManager> 必須設置 EnablePageMethods="true"。public static,並標記 [System.Web.Services.WebMethod] 屬性。需引用 System.Web.Services 命名空間。<%@ Page ... %> 指令一起複製,會導致 CodeFile、Inherits 屬性與實際類別不符,造成 PageMethods 代理生成失敗。此錯誤無編譯提示,極易被忽略。Sys.Application.load 事件或 $(document).ready() 之後呼叫 PageMethods,避免腳本載入順序問題。<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="Demo" %>
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
// 後端
[WebMethod]
public static string GetServerTime()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
// 前端
function showTime()
{
PageMethods.GetServerTime(onSuccess, onError);
function onSuccess(result) { alert(result); }
function onError(err) { console.error(err); }
}
排查時建議開啟瀏覽器開發者工具 (F12) 觀察 Network 與 Console 面板,確認 ScriptResource.axd 載入狀態及生成的 PageMethods 代理代碼。