How to connect jQuery with WCF

Consuming WCF services using jQuery and ASP.net can be very difficult for the first time, and I will attempt to make the process a little bit more palatable. I plan to make this tutorial overly tedious, so bear with me.
We start by creating a blank asp.net website.
 
We create a new Class Library project to house our objects. Next we need to create some kind of object to send to our future web page.   I like to be very original, and will thus name it HelloWorld.cs. Next I will add a couple properties, FirstProperty and SecondProperty. In order for our new class to be serialized, we must at a new reference in our project to System.Runtime.Serialization, and decorate our class with a DataContract attribute and our methods with a DataMember attribute. Finally, add a new project reference to our new class library in the website.
 
 

Now that our HelloWorld object is ready, let’s create a new directory in our website named Services, and then add a new WCF Service named HelloWorldService.svc.  Visual Studio is automatically going to create an interface and matching concrete class in the App_Code directory for us. Open up IHelloWorldService.cs and add a new method called Run() that returns a HelloWorld object. Now open up HelloWorldService.cs and implement the same Run() method. In the Run() method we will simply create a new HelloWorld instance and return it. Make sure to delete the default DoWork() method, because working is lame. Since we will be consuming the service with AJAX add the following to your code. [WebInvoke(Method="POST", BodyStyle=WebMessageBodyStyle.Wrapped, ResponseFormat=WebMessageFormat.Json)]  Right click on the solution and build it ( this is very important! If you do not build it before you add a new service reference, it will ungracefully error out).

 
Now comes everyone’s favorite part, configuration. Right click on the web project and add a new service reference. Click the Discover button and our HelloWorldService will show up in the address bar. In the Namespace textbox enter HelloWorldService and click “OK”. Visual Studio will add a new reference to the service in the App_WebReferences directory.  



Open up the sites web.config. Then navigate to the <system.serviceModel> section.  When the service reference was added, Visual Studio created new generic binding named <wsHttpBinding>. We want to first delete this entire section. Now add a new section called <customBinding> Next, create a child section under our customBinding called <binding name="WebHttpBinding_IHelloWorldService" then add:
 
<textMessageEncodingmaxReadPoolSize="64"maxWritePoolSize="16"
            messageVersion="Soap12"writeEncoding="utf-8">
            <readerQuotasmaxDepth="32"maxStringContentLength="8192"maxArrayLength="16384"
              maxBytesPerRead="4096"maxNameTableCharCount="16384" />
 </textMessageEncoding>
 
Your finished block should look like:
<bindings>
          <customBinding>
            <bindingname="WebHttpBinding_IHelloWorldService">
             <textMessageEncodingmaxReadPoolSize="64"maxWritePoolSize="16"
            messageVersion="Soap12"writeEncoding="utf-8">
                <readerQuotasmaxDepth="32"maxStringContentLength="8192"maxArrayLength="16384"
                  maxBytesPerRead="4096"maxNameTableCharCount="16384" />
              </textMessageEncoding>
            </binding>
          </customBinding>
 </bindings>
 
Now we need to edit the endpoint section of the web.config. First delete the attribute “address”, then change the binding attribute to customBinding to reference the customBinding block we just configured. Next we need to change the bindingConfiguration and the name attribute to WebHttpBinding_IHelloWorldService. Finally, delete the identity section in the client tags. Our final client tag should look like:
 
        <client>
            <endpointbinding="customBinding"bindingConfiguration="WebHttpBinding_IHelloWorldService"
                contract="HelloWorldService.IHelloWorldService"name="WebHttpBinding_IHelloWorldService">
            </endpoint>
        </client>
 
Now its time to edit the behaviors area. Depending upon your desierd setup this can get altered many different ways. For this example, go ahead and add a new endpointBehaviors section to the <behaviorstag:
 
<endpointBehaviors>
        <behaviorname="WebBehavior">
          <webHttp />
        </behavior>
 </endpointBehaviors>
 
The behaviors tag will include a <serviceBehaviors> section. The only thing we need to add to this section is an empty httpGetUrl attribute to the serviceMetadata section. Your <serviceBehaviors> section should now look like:
 
<serviceBehaviors>
            <behaviorname="HelloWorldServiceBehavior">
                <serviceMetadatahttpGetEnabled="true"httpGetUrl="" />
                <serviceDebugincludeExceptionDetailInFaults="false" />
          </behavior>
 </serviceBehaviors>
 
The last piece of configuration we need to edit is the <services tag. First change the
 

<endpoint address="" binding="wsHttpBinding" contract="IHelloWorldService">

 
to
 

<endpoint address="" binding="webHttpBinding" behaviorConfiguration="WebBehavior" contract="IHelloWorldService">

 
Then delete the <identity> section and its contents. Believe it or not, we are now finished with the config section. The final config should look like:

<system.serviceModel>
        <bindings>
          <customBinding>
            <bindingname="WebHttpBinding_IHelloWorldService">
              <textMessageEncodingmaxReadPoolSize="64"maxWritePoolSize="16"
            messageVersion="Soap12"writeEncoding="utf-8">
                <readerQuotasmaxDepth="32"maxStringContentLength="8192"maxArrayLength="16384"
                  maxBytesPerRead="4096"maxNameTableCharCount="16384" />
              </textMessageEncoding>
            </binding>
          </customBinding>
        </bindings>
        <client>
            <endpointbinding="customBinding"bindingConfiguration="WebHttpBinding_IHelloWorldService"
                contract="HelloWorldService.IHelloWorldService"name="WebHttpBinding_IHelloWorldService">
            </endpoint>
        </client>
        <behaviors>
          <endpointBehaviors>
            <behaviorname="WebBehavior">
              <webHttp />
            </behavior>
          </endpointBehaviors>
            <serviceBehaviors>
                <behaviorname="HelloWorldServiceBehavior">
                    <serviceMetadatahttpGetEnabled="true"httpGetUrl="" />
                    <serviceDebugincludeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <servicebehaviorConfiguration="HelloWorldServiceBehavior"name="HelloWorldService">
                <endpointaddress=""binding="webHttpBinding"behaviorConfiguration="WebBehavior"contract="IHelloWorldService">
                </endpoint>
                <endpointaddress="mex"binding="mexHttpBinding"contract="IMetadataExchange" />
            </service>
        </services>
    </system.serviceModel>
 
In order to connect to WCF from jQuery, we will need to add a few scripts to our solution. First we need to add the serviceProxy.js and ww.jquery.js files to our solution courtesy of Rick Strahl. You can find another great post (probably better than this one) and these two files at Rick Strahl’s blog http://www.west-wind.com/weblog/posts/896411.aspx.
 
 
Open up your Default.aspx page and add your JavaScript references.  In the form tag add:
 
<inputid="testButton"type="button"value="Test"/>
       
        <ulclass="list"></ul>
 
Now add a scipt block somewhere and add:
 
<scripttype="text/javascript">
            var proxy;
            var proxyLocation = " /Services/HelloWorldService.svc/";
 
            $(document).ready(function() {
                proxy = new ServiceProxy(proxyLocation);
 
                $("#testButton").click(buttonClicked);
            });
 
            function buttonClicked() {
                proxy.invoke("Run",
                                    null,
                                    function(result){
                                        $(".list").append(
                                             $("<li>" + result.FirstProperty + "</li><li>" + result.SecondProperty + "</li>")
                                            );
                                    }
                        );
            }
        </script>
 
The proxyLocation variable is the actual location to the WCF service file you created. Make sure to add a “/” to the end of the path, as this will allow you to append the method name to the service. Visual Studio will like to add the application domain to the front of your paths; make sure you add this to your proxyLocation path for testing with localhost. When the button is clicked, the buttonClicked() method is fired and the invoke method from serviceProxy.js is called. The first argument is the desired method name, the second is any overloads that the method might take in e.g. { firstArgument : “some text”, secondArgument: “some more text” }. Our test method Run() does not have any overloads, so we will set it to null. Finally, we add a result handler function which parses the result and appends our <ul>. In our example the returned properties are returned as a single nested object. If your WCF service returns a List<> of objects,  just add the object name and then loop through them.
 
for (var i = 0; i < result.HelloWorld.length; i++) {
                            $(".list").append(
                                $("<li>" + result. HelloWorld [i]. FirstProperty + "</li><li>" + result. HelloWorld [i]. SecondProperty + "</li>")
                            );
                        }
 
Click here to download the source used in this example.