b

Wednesday, 2 January 2013

AJAX Enabled WCF Service in ASP.NET 4.5

Step 1)  Create a Empty ASP.NET Website. Name it as AjaxEnableWebsite


Ajax Enabled WCF Service in Asp.NET 4.5



AJAX Enabled WCF Service in ASP.NET 4.5


Step2)  Add new item by selecting "Ajax-Enabled WCF Service" Name it as "SuperAjaxWCF"

Replace DoWork default method(added by Framework).

[OperationContract]
    public String DoWork()
    {
        // Add your operation implementation here
        return String.Format("Today's date:{0:D}",System.DateTime.Now);
    }


Step 3) Add New item Web Form and name it as Default

AJAX Enabled WCF Service in ASP.NET 4.5










In the Default.aspx
  •            Add ScriptManager
  •            Add Button Server Control
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
            <Services>
                <asp:ServiceReference Path="~/SuperAjaxWCF.svc" />
            </Services>
        </asp:ScriptManager>
        <br />
        <br />
        <asp:Button   ID="Button1" runat="server"
Text="Call Ajax Enabled WCF"
OnClientClick="javascript:calling_WCF_in_Javascript();" />
        <br />
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
        <div style="color:green;font-size:2em;border-width:thick;border-color:red;" id="wcf_ajax_response" runat="server">
            No Ajax Response
        </div>

            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger
ControlID="Button1" EventName="Click" />
            </Triggers>
        </asp:UpdatePanel>

Step 4) Add Javascript Code for Creating  AJAX-WCF Service.

<head runat="server">
    <title>AJAX-Enabled WCF Service Example</title>
    <script type="text/javascript">

        function calling_WCF_in_Javascript() {
            try{
                var proxy = new SuperAjaxWCF();
             //Creating a WCF Service in javascript using proxy class generated by
             //ScriptManager
                //note NameSpace is Empty.
           
                //Calling WCF methods in javascript.
                proxy.DoWork(onSuccess, OnFailed, null);
            }
            catch(error)
            {
                alert(error.message);
            }
        }

        function onSuccess(result) {
           // alert("<font size=20>" + result + "</font>");
            document.getElementById('wcf_ajax_response').innerHTML = result;
        }

        function OnFailed(result) {
            alert(result);
        }
    </script>
</head>

Step 5)  Run the Application

AJAX Enabled WCF Service in ASP.NET 4.5
AJAX Enabled WCF Service in ASP.NET 4.5










Note:  No web.config changes required in .NET 4.5

Happy Coding...

No comments:

Post a Comment