能否从JavaScript调用ASP.NET代码后台函数?
我更喜欢Muhammad Akhtar的PageMethod方法。只有一个小提示:你不需要ScriptManager。ScriptManager只是为您生成JavaScript代理方法。如果您的页面已经有jQuery,您可以忘记ScriptManager并在您的页面上编写类似于下面这样的代码:
<script type ="text/javascript">
$(document).ready(function() {
$("#AjaxLink").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "YourPage.aspx/updateContent",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
$("#content").html(result.d);
}
});
});
});
</script>
这假设您的页面上有一个ID为AjaxLink的链接和一个显示结果的ID为content的div元素。 好处是相比于使用jQuery和脚本管理器注入的脚本,可以节省30kb的Javascript。
是的,您可以创建类似于以下示例的 Web 方法:
<WebMethod(EnableSession:=True), ScriptMethod()> _
Public Shared Function updateContent() As String
Return "Your String"
End Function
PageMethods.updateTabContent(parameterValueIfAny, onSuccessMethod,onFailMethod);
this also need to add
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
ScriptManager
才能使其正常工作吗?请展示一下标记,谢谢。 - John Saunders[System.Web.Services.WebMethod]
public static string set_single_amount(arg a1)
{
return value;
}
$("#control").click(function()
{
PageMethods.set_single_amount(value,afercalling)
});
function afercalling(result)
{
alert(result);
}
如果您正在开发一个非Ajax项目,可以尝试使用System.Web.UI.ICallbackEventHandler。
这里有一些示例:
http://msdn.microsoft.com/en-us/library/ms178210.aspx
http://www.ajaxmatters.com/2006/05/using-icallbackeventhandler-in-asp-net/