HTML `` 是純客戶端控制項,無法直接觸發伺服端事件(如 `
<%@ WebHandler Language="C#" Class="MyHandler" %>
using System.Web;
public class MyHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "application/json";
string action = context.Request["action"];
if ("doSomething".Equals(action)) {
// 業務邏輯
context.Response.Write("{\"success\":true,\"msg\":\"完成\"}");
}
}
public bool IsReusable => false;
}
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| ASHX Handler | 輕量、無 ViewState、效能佳 | 需手動處理序列化 | 簡單 AJAX 端點 |
| Web API Controller | RESTful、屬性路由、內建內容協商 | 較重、需路由設定 | 標準 API 服務 |
| PageMethod (ScriptManager) | 無需獨立端點、型別安全 | 需 ScriptManager、ViewState 開銷 | WebForms 既有專案 |
| __doPostBack | 觸發完整頁面生命週期 | 全頁回傳、體驗差 | 極少數相容需求 |