views:

1360

answers:

2

Hi, 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.

A: 

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>
Chris Lively
And in javascript how do you access it?
Paleta
But If I am to call a class method, hoy do you references it. ServiceReference is not possible because is a class method, not an .asmx file.
Paleta
The asmx file should simply expose your class.
Chris Lively
+1  A: 

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"&gt;


<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>
korchev
Didn't know about regular page methods. Nice.
Chris Lively
I know this, I'm just trying to call any class method.
Paleta