ASP.NET WebForms 頁面生命周期中,<%= %> 表達式在服務端渲染階段執行,輸出結果直接嵌入 HTML/JS 代碼中。JS 運行時看到的已是渲染後的字面值。
// Default.aspx.cs
public partial class Default : System.Web.UI.Page {
protected string GetServerTime() {
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
}
// Default.aspx
// Default.aspx.cs
public string ProcessData(string input) {
return "處理結果:" + input.ToUpper();
}
// Default.aspx
| JS 變量值 | 內聯寫法 | 渲染結果 |
|---|---|---|
"hello" | '<%= Method("' + val + '") %>' | "結果內容" |
'hello' | "<%= Method('" + val + "') %>" | '結果內容' |
| 含單雙引號混合 | 用 \' 或 \" 轉義 | 視情況 |
// Default.aspx.cs
[WebMethod]
public static string ProcessData(string input) {
return "處理結果:" + input.ToUpper();
}
// Default.aspx (jQuery)
function callWithParam() {
const input = $("#txtInput").val();
$.ajax({
type: "POST",
url: "Default.aspx/ProcessData",
data: JSON.stringify({ input: input }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d); // WebMethod 返回值在 .d 屬性
}
});
}
WebForms 已停止積極開發,新項目建議使用 ASP.NET Core MVC/Razor Pages + Web API,前後端完全分離:
// Controller
[HttpPost]
public IActionResult ProcessData([FromBody] string input) {
return Ok(new { result = "處理結果:" + input.ToUpper() });
}
// 前端 fetch
fetch('/api/data/process', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input)
}).then(r => r.json()).then(data => alert(data.result));
<%= %> 輸出未編碼,若 C# 返回用戶輸入需 HttpUtility.JavaScriptStringEncode()