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

Posted by: Suprotim Agarwal , on 11/26/2008, in Category ASP.NET
Views: 94459
Abstract: In this article, we will see how to create an AJAX-enabled WCF Service and how to consume it using client-side script in an ASP.NET page. I have kept the example quiet simple so in order to keep our focus on creating and consuming AJAX Enabled WCF Services.
Access an AJAX Enabled WCF Service using ASP.NET and Client Script
 
In this article, we will see how to create an AJAX-enabled WCF Service and how to consume it using client-side script in an ASP.NET page. I have kept the example quiet simple so in order to keep our focus on creating and consuming AJAX Enabled WCF Services.
What is AJAX Enabled WCF Service by the way?
In simple words, AJAX-enabled WCF Service is a service that can be consumed using an AJAX client-side script. 
The easiest method to create an AJAX-enabled WCF Service is to use the ‘AJAX-enabled WCF Service’ Template in Visual Studio. Let us see how.
Step 1: Create an ASP.NET 3.5 website
Step 2: Right click the project > Add New Item > Choose ‘AJAX-enabled WCF Service’ from the Templates > name the service as ‘GreetingService’ > Add.
Template
Step 3: If you observe the GreetingService.cs/GreetingService.vb gets added in the App_Code directory. The GreetingService.svc serves as the EndPoint. Also observe the web.config that now contains the <system.serviceModel> to describe your new endpoint. This endpoint enables us to create a client-side AJAX proxy class, which in turn can be used to call our service.
Open the GreetingService.cs or vb to implement operations to be exposed in the service. Specify the Namespace for ServiceContractAttribute as ‘GreetNM’:
[ServiceContract(Namespace = "GreetNM")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class GreetingService
{
Note: For users who are familiar with client side web service calls in an ASP.NET AJAX Extensions-enabled page, will observe that the class namespace is used in the WCF service and not in the client proxy.
Add a new method called GreetUser(string uname) which takes a username and returns a string with the “Hello” greeting appended to the user name. Decorate the method with the ‘OperationContractAttribute’ to indicate that the method is a part of the contract.
C#
      // Add more operations here and mark them with [OperationContract]
    [OperationContract]
    public string GreetUser(string uname)
    {
        return "Hello " + uname;
    }
 
VB.NET
    ' Add more operations here and mark them with <OperationContract()>
    <OperationContract()> _
    Public Function GreetUser(ByVal uname As String) As String
        Return "Hello " & uname
    End Function
Step 4: Now open Default.aspx. Go the Design mode and drag and drop a <ScriptManager> from the AJAX Extensions tab in the toolbox. With the ScriptManager selected, open the ‘Services’ collection in the Properties window
Script Service
The ‘ServiceReference Collection Editor’ window opens up. Click Add and in the Path specify ‘GreetingService.svc’ > OK.
ServiceRef
If you go back to the Source view, the action adds a ServiceReference to the <Services> element
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="~/GreetingService.svc" />
            </Services>
        </asp:ScriptManager>
You can also directly add the reference instead of using the ServiceReference Collection Editor. What we have essentially done is that we have registered the AJAX-enabled WCF service with the ScriptManager by adding a ServiceReference and specifying the address to the GreetingService.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 GreetNM namespace. If you remember, we added a namespace to the service called ‘GreetNM’.
[ServiceContract(Namespace = "GreetNM")]
 
Hence when the client-side script proxy is created, it is now in the GreetNM namespace.
Intelli
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 GreetNM.GreetingService();
            greeto.GreetUser($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
How does the AJAX-enabled WCF service work internally?
I would recommend you reading this post. The internal working along with the JSON serialization/deserialization has been explained very well in this blog.
Well that was a simple introduction to AJAX-enabled WCF Service. An even simpler way to create script services is to use Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" in your .svc file.
<%@ ServiceHost Language="C#" Debug="true" Service="GreetingService" CodeBehind="~/App_Code/GreetingService.cs" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>
This Factory, automatically adds an ASP.NET AJAX endpoint to a service, without you needing to add the configuration details in the web.config file.
That’s it for now. In future posts, we will see some practical examples of using AJAX-enabled WCF service. Until then, stay tuned! I hope you liked the article and I thank you for viewing it. The entire source code of this article can be downloaded from here.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Raj on Monday, December 29, 2008 11:40 AM
Nice aritcle. You won't believe...I had decided to lean today something on AJAX enabled WCF and got a chance to read your article to get brief introduction on concept. Although I could understand how everything is working, I am at lsot on the pre requistes required to understnad the whole concept. Could you please let me know what I need to learn to understnad statements like [ServiceContract(Namespace = "GreetNM")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
Comment posted by Henllyee Cui on Monday, December 29, 2008 9:27 PM
ServiceContract is a property of WCF。
Comment posted by Thanigainathan on Wednesday, December 31, 2008 11:05 PM
Hi,

Thanks for the info . Thanks for sharing the link to internal workings of Ajax.

Thanks ,
Thani
Comment posted by Nisheeth on Tuesday, April 7, 2009 2:43 AM
<a href="http://nisheethpandya.blogspot.com">Thanks a lot</a>
Comment posted by Adam Burns on Wednesday, December 30, 2009 5:44 PM
I don't get the web.config section, when I add the service, I get an error instead about system.ServiceModel.Configuration.WebScriptEnablingElement, System.ServiceModel.Web ..... is not registered in the collection 'behaviorExtentions'

Any ideas why?
Comment posted by Fleet Tracking on Thursday, November 4, 2010 2:07 AM
Trying to host a REST enabled WCF service on IIS 5.0 throuw the following error: "IIS specified authentication schemes 'IntegratedWindowsAuthentication, Anonymous', but the binding only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous. Change the IIS settings so that only a single authentication scheme is used." If i remove the windows authentication i get 404 not found, so - am i missing something? if this cannot run on IIS than i will not be able to deploy it. Please help!!! I tried using the WebServiceHostFactory in the svc file, and also tries using only configuration, and even tried to use a custom factory that adds the webHttpBinding and behavior on the endpoint by code. none of them works. (Self hosting is working, the problem is when this is hosted on IIS). is this related to IIS 5.0? I tries both VS2005 and VS 2008 RTM - some problem.
[url=http://www.trackcompare.co.uk/vehicle-fleet-tracking]Fleet Tracking[/url]

http://www.trackcompare.co.uk/vehicle-fleet-tracking
Comment posted by Swathi on Thursday, April 7, 2011 3:52 AM
Hi ur Article nice,It is working also,but i am not understanding y we r using greeting='nm' name space and tell me how it is work please help me.....
Comment posted by Michael Arnold on Wednesday, February 1, 2012 1:20 PM
Great Post! Thank you
Comment posted by Sonal on Tuesday, October 29, 2013 12:04 AM
How can i upload file from jquery ajax call and get that file in .svc webservice?Can anyone tell me please