我在 aspx 页面中有一个用于 HTML img 单击事件的 javascript 函数。以及其代码隐藏页面中的服务器方法。现在我想仅在用户单击 HTML img 时从 javascript 函数调用服务器方法而不带任何参数。
C# 代码隐藏方法:
[WebMethod]
public void PopUpClick(object sender, EventArgs e)
{
//Something;
}
JavaScript 方法:
$(document).ready(function () {
$('.clickme').click(function () {
PageMethods.PopUpClick();
});
});
我还在母版页中添加了:<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true" />
它不工作。当我在 Chrome 上调试这个 Javascript 函数时 我看到一个错误:Uncaught Reference Error:PageMethods is not defined。
最佳答案
.aspx
<div>
<p>Say bye-bey to Postbacks.</p>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
</div>
JavaScript
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
C#
[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
return result;
}
关于c# - 如何从 javascript 函数调用代码隐藏方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510749/