问题
I've created a particular server control that has some methods I'd like to call from javascript. I know that the ScriptManager allows to call a web service or a page method. But I'd like to call a particular class method (I can do this with Anthem or even AjaxPro.NET). Is there a way to accomplish this using ScriptManager?
Thanks.
回答1:
The class needs to be exposed as a web service. Then you can use JSON to access it client side
For example: (In an ASMX file such as Address.asmx)
[ScriptService]
[WebService(Namespace = "JsonPanels.Services")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Address : WebService {
[WebMethod]
public String LoadAddress() {
return "some values...";
} // webmethod::StoreValues
}
In the pages aspx file you will need a scriptmanager that references the web service:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Services/Address.asmx" />
</Services>
</asp:ScriptManager>
Your javascript function will look like:
<script type="text/javascript">
function callLoadAddress() {
JsonPanels.Services.Address.LoadAddress(GetLoadAddress_success, OnFailed);
}
function GetLoadAddress_success(e) {
var result = e;
$get('resultAddress').innerHTML = result;
}
// --------------------------
function OnFailed() {
$get('resultFailed').innerHTML = "failed";
}
</script>
回答2:
Apart from web services (asmx or WCF) you can also call page methods. Those are static methods of your Page decorated with the [WebService] attribute. You also need to set the EnablePageMethods property of the script manager to true. Here is a quick sample:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
[WebMethod]
public static int AddOne(int arg)
{
return arg + 1;
}
</script>
<html>
<head id="Head1" runat="server">
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<script type="text/javascript">
function doAdd ()
{
PageMethods.AddOne(2);
}
</script>
<a href="javascript: doAdd()">click me</a>
</form>
</body>
</html>
来源:https://stackoverflow.com/questions/634661/how-do-i-call-a-particular-class-method-using-scriptmanager