Access an AJAX Enabled WCF Service using ASP.NET and Client Script

Sunday 28 December 2014

Access an AJAX Enabled WCF Service using ASP.NET and Client Script

registered the AJAX-enabled WCF service with the ScriptManager by adding a ServiceReference and specifying the address to the MyService.svc.
The ScriptManager in turn will generate the script to create the client proxy through an HTTP handler.
Step 5: Now add a HTML Button, an HTML Input box and a <div> to the Default.aspx page. After renaming the controls and adding the onClick event of the
button, the markup will appear similar to the following:
        <input id="btnCallWCF" type="button" value="Greet User" onclick="return btnCallWCF_onclick()" />
        <input id="txtUNm" type="text" />    
 <div id="dispGreeting">
The JavaScript code for the click event is as shown below:
   <script language="javascript" type="text/javascript">

        function btnCallWCF_onclick() {

        }

    </script>
</head>
Step 6: Call the service. You will notice how the intellisense brings up the SCANM namespace. If you remember, we added a namespace to the service called
 ‘SCANM’.
[ServiceContract(Namespace = "SCANM")]

Hence when the client-side script proxy is created, it is now in the SCANM namespace.

Add code to call the WCF Service using client side script as shown below
<head runat="server">
    <title>Create AJAX-enabled WCF Service</title>

    <script language="javascript" type="text/javascript">

        function btnCallWCF_onclick() {
            var greeto = new SCANM.MyService();
            greeto.FunctionNm($get("txtUNm").value, OnGreetingComplete, OnError);

        }

        function OnGreetingComplete(result) {
            $get("dispGreeting").innerHTML = result;
        }

        function OnError(result) {
            alert(result.get_message());
        }
    </script>
</head>

The results are shown below.
Results