ASP.NET Web Forms 時代常需在前端 JavaScript 呼叫後端 C# 邏輯。本文整理三種主流方式,並解決中文亂碼核心問題:頁面編碼宣告一致性。
// .aspx.cs 後端
protected string GetSiteUrl()
{
return "https://www.example.com";
}
特點:頁面渲染階段執行、同步阻塞、適合簡單資料輸出。
// .aspx.cs
protected void RenderSiteUrl()
{
Response.Write("https://www.example.com");
}
注意:Response.Write 會直接輸出至回應流,位置取決於 `<% %>` 在頁面的位置。
// .aspx.cs
protected void btnHidden_Click(object sender, EventArgs e)
{
// 執行伺服器端邏輯
lblResult.Text = "伺服器時間: " + DateTime.Now;
}
適用:需觸發完整頁面生命週期、更新 ViewState、綁定 GridView 等場景。
// .aspx.cs - 必須 static
[System.Web.Services.WebMethod]
public static string GetServerTime()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
data: JSON.stringify({ id: 123 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
console.log(response.d); // ASP.NET 包裝在 .d 屬性
}
});
// Controller
[HttpGet("api/time")]
public IActionResult GetTime() => Ok(DateTime.Now);
// 前端 (Razor Pages / Blazor / SPA)
fetch('/api/time')
.then(r => r.json())
.then(data => console.log(data));
| 層級 | 設定 | 關鍵點 |
|---|---|---|
| ASPX 頁面指令 | <%@ Page ContentType="text/html; charset=utf-8" ResponseEncoding="utf-8" %> | ResponseEncoding 決定輸出編碼 |
| HTML Meta | <meta charset="utf-8"> | 瀏覽器解碼依據 |
| Web.config | <globalization requestEncoding="utf-8" responseEncoding="utf-8" /> | 全站預設 |
| JS 檔案 | 檔案儲存為 UTF-8 (無 BOM) | Visual Studio 預設可能是 Big5 |
| 資料庫連線 | 連接字串無需特殊設定 (SQL Server 內部 Unicode) | NVarChar 儲存 Unicode |
| 資料庫欄位 | 使用 NVARCHAR 而非 VARCHAR | 避免編碼轉換損失 |
在 `.aspx` 頁面**第一行**加入:
<%@ Page ContentType="text/html; charset=utf-8" ResponseEncoding="utf-8" %>
這比修改 Web.config 更精確、立即生效、不影響其他頁面。
// 快速診斷:在 Page_Load 寫入
Response.Write("測試中文"); // 觀察瀏覽器顯示
Response.Write($"");
前端呼叫後端方式演進:內嵌運算式 → 隱藏按鈕 PostBack → PageMethod/WebMethod → Web API → Minimal API。亂碼本質是編碼不一致,**統一全鏈路 UTF-8** 是唯一正解。新專請直接採用 ASP.NET Core Web API + 前端框架,避開 Web Forms 生命週期複雜度。