How to use “Ajax Enabled WCF” in asp.net ?


Hi

“Ajax Enabled WCF ” is mainly used to consume the wcf service in client side using ajax.

Using Script mangaer and Javascript we can easily call the wcf service.

Here is the few steps to do this task.

Step1. Create the asp.net project

Step2: Add the “Ajax Enabled WCF” like this image.

Step3: Write the method in WCF like this

using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

[ServiceContract(Namespace = “”)]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class Service
{
// Add [WebGet] attribute to use HTTP GET
[OperationContract]
public int CostOfBook(int quantity)
{
return 200 * quantity;
}

}

Step4: Compile the code.

Step5: Add the  Ajax scriptmanger and consume the service like this

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

<Services>

<asp:ServiceReference Path=”~/Service.svc” />

</Services>

</asp:ScriptManager>

Step5: Take one Html Textbox control and Button control and write the Javascript like this

<script language=”javascript” type=”text/javascript”>
function Button1_onclick()
{

Service.CostOfBook(document.getElementById(‘txtNoOfBook’).value, onSuccess, null, null);

}

function onSuccess(result)
{
//alert(result);
$get(“lblmsg”).innerText =”Total Price of book is ” +result;

//alert(“Total Price of book is ” +result);
}

</script>

The complete HTML code is like this

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
<script language=”javascript” type=”text/javascript”>
function Button1_onclick()
{

Service.CostOfBook(document.getElementById(‘txtNoOfBook’).value, onSuccess, null, null);

}

function onSuccess(result)
{
//alert(result);
$get(“lblmsg”).innerText =”Total Price of book is ” +result;

//alert(“Total Price of book is ” +result);
}

</script>

<style type=”text/css”>
.style1
{
width: 100%;
}
.style2
{
width: 324px;
}
</style>

</head>
<body>
<form id=”form1″ runat=”server”>
<div>

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

<Services>

<asp:ServiceReference Path=”~/Service.svc” />

</Services>

</asp:ScriptManager>

<br />

</div>
<table class=”style1″>

<td align=”right”>
No of books</td>
<td>
<input id=”txtNoOfBook” type=”text” /></td>
</tr>
<tr>
<td class=”style2″>
&nbsp;</td>
<td>

<input id=”Button1″ type=”button” value=”Submit” onclick=”return Button1_onclick();” /></td>
<td>
&nbsp;</td>
</tr>
<tr>
<td class=”style2″>
&nbsp;</td>
<td>
<asp:Label ID=”lblmsg” runat=”server” Text=””></asp:Label>
</td>
<td>
&nbsp;</td>
</tr>
</table>
</form>
</body>
</html>

You can download source code from here

Advertisements
Posted in Ajax, WCF. 6 Comments »

6 Responses to “How to use “Ajax Enabled WCF” in asp.net ?”

  1. santhosh Says:

    Good article 🙂 v simple and understandable for beginners 🙂 Thx

  2. Chandra Dev Says:

    Thank you.I understand the problem of beginners. So i try to write article in simple manner.

  3. brian Says:

    Error: “Service is undefined”

    I’ve tried everything, first and foremost following this tutorial TO THE LETTER in my existing ASP.NET solution. I have been fighting this for over 5 days now: javascript complains: “Service is undefined” when clearly it’s defined! I am tearing out my hair over this, WHAT IS WRONG?!?!

    Under vstudio2010

    web.config

        <system.serviceModel>
          <behaviors>
            <endpointBehaviors>
              <behavior name="web">
                <webHttp/>
              </behavior>
            </endpointBehaviors>
            <serviceBehaviors>
              <behavior name="HttpGetMetadata">
                <serviceMetadata httpGetEnabled="true" />
              </behavior>
              <behavior name="">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="false" />
              </behavior>
            </serviceBehaviors>
          </behaviors>
          <services>
            <service name="MyService" behaviorConfiguration="HttpGetMetadata">
              <endpoint address="" binding="webHttpBinding" contract="IMyService" behaviorConfiguration="web"></endpoint>
              <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
            </service>
          </services>
          <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
        </system.serviceModel>
    

    MyService.svc

    <%@ ServiceHost Language="C#" Debug="true" Service="WebSolution.MyService" CodeBehind="MyService.svc.cs" 
    Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
    

    MyService.svc.cs

    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.ServiceModel.Web;
    using System.Data;
    using System.Xml;
    using System.ServiceModel.Activation;
    
    namespace WebSolution
    {
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MyService" in code, svc and config file together.
        [ServiceContract(Namespace = "WebSolution")]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    
        public class MyService
        {
            [OperationContract]
            [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/GreetUser/{uname}")]
            public string GreetUser(string uname)
            {
                return "Hello " + uname;
            }
        }
    }
    

    MyServiceTest.aspx.cs:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyServiceTest.aspx.cs" Inherits="WebSolution.MyServiceTest" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
            <script language="javascript" type="text/javascript">
    
                function btnCallWCF_onclick() {
                    var envupdatesvc = new MyService();
    //not going to bother going further than this, the error is RIGHT HERE!
                }
    
            </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
                <Services>
                    <asp:ServiceReference Path="~/MyService.svc" />
                </Services>
            </asp:ScriptManager>
            <input id="btnCallWCF" type="button" value="Greet User" onclick="return btnCallWCF_onclick()" />
            <input id="txtUNm" type="text" /> 
            <div id="dispGreeting">
            </div>
        </div>
        </form>
    </body>
    </html>
    
  4. omer Says:

    is missing in your endpoint behaviour configuration. use this lines

  5. omer Says:

    in the web.config file. The enableWebScript tag is missing in your endpoint behaviour configuration HttpGetMetadata

  6. Al Says:

    Hi to every one, because I am in fact keen of reading this web site’s post to
    be updated daily. It includes pleasant stuff.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: