在 ASP.NET 開發中,我們常需要在前端 JavaScript 裡調用後台 C# 的方法。不帶參數的情況很簡單,但一旦方法帶有參數,引號的運用就成了容易踩雷的關鍵。本文透過實例說明兩種情況。
後台 C# 方法:
public string test()
{
return "Hello World";
}
ASPX 頁面:
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>無標題頁</title>
<mce:script type="text/javascript" ><!--
var demo=function(){
var b= "<%=test() %>";
alert(b);
}
// --></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="id1" onclick="demo()" value="JS調用CS" />
</div>
</form>
</body>
</html>
後台 C# 方法:
public string test(string a)
{
return a;
}
ASPX 頁面:
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>無標題頁</title>
<mce:script type="text/javascript" ><!--
var demo=function(){
var a="Hello World";
var b= '<%=test("'+a+'") %>';//這裡一定注意單引號和雙引號的使用!!!!!
alert(b);
}
// --></mce:script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="id1" onclick="demo()" value="JS調用CS" />
</div>
</form>
</body>
</html>
帶參數的調用寫作 '<%=test("'+a+'") %>'——外層一定要用單引號把 <%= %> 包起來,裡面的字串參數則用雙引號。這個層層嵌套的引號規則是成敗的關鍵,否則調用就會失敗。掌握好單引號與雙引號的搭配,這個問題便迎刃而解。