無參數呼叫
<%@ Page Language="C#" %>
<script runat="server">
public string GetMessage() { return "Hello from C#"; }
</script>
<html><head>
<script>
function callCs() {
var msg = '<%= GetMessage() %>'; // 伺服器端渲染成字串常值
alert(msg);
}
</script></head><body>
<button onclick="callCs()">呼叫 C#</button></body></html>
帶參數呼叫 (關鍵:引號巢狀)
<script runat="server">
public string Echo(string s) { return "C# 收到:" + s; }
</script>
<script>
function callCsWithParam() {
var input = '測試參數';
// 單引號包外層,雙引號包內層字串常值
var result = '<%= Echo("' + input + '") %>';
alert(result);
}
</script>
引號巢狀規則口訣
'<%= Method("' + jsVar + '") %>'
// 外層單引號 → JS 字串
// 內層雙引號 → C# 字串常值
// jsVar 為 JS 變數,會先拼接再輸出到伺服器端標記
⚠️ 重要限制
- 此為**伺服器端渲染**技巧,非真正 AJAX 呼叫
- 頁面載入時 C# 方法已執行完畢,結果內嵌在 JS 中
- 真正非同步呼叫請用 `` + `PageMethods`、Web API、或 `fetch` 呼叫 `.ashx`/`.asmx`
現代建議架構
// 前端
fetch('/api/echo', { method:'POST', body:JSON.stringify({s:'test'}), headers:{'Content-Type':'application/json'} })
.then(r=>r.json()).then(d=>alert(d.msg));
// 後端 (ASP.NET Core Controller)
[HttpPost] public IActionResult Echo([FromBody]Req req) => Ok(new { msg = "C# 收到:" + req.s });