Sunday, February 14, 2010

Ajax Enabled WCF Service

Introduction

        In this article, we are going to see how to use Ajax Enabled WCF Service in a website. Let us go through this application Step by Step.


Step1:


       Open VS2008->create new website->name it->Right click on the website->Add new item ->Select Ajax Enabled WCF Service->name it as Service.svc which is by default at the first instance.



 


Step2:


     Now lets write simple lines of code in service.cs class which is located in App_code folder.




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 string HelloWorld()


{


// Add your operation implementation here


return "Hello World";


}


// Add more operations here and mark them with [OperationContract]


}


This HelloWorld method just returns simple string value as HelloWorld.


 


Step3:


       Now lets go to Default.aspx->Add new ScriptManger->give service reference to Service.svc


      


Here we added html button and a span. Click on the html button automatically it will script tag.


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


function Button1_onclick() {


}


</script>


Within the Button1_onclick function writes these lines


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


// <!CDATA[


function Button1_onclick() {


Service.HelloWorld(onsuccess,onfailed,"Hello world example");


}


function onsuccess(results)


{


message.innerHTML=results;


}


function onfailed(results)


{


message.innerHTML=results;


}


// ]]>


</script>


 


Step4:


       Now lets go to the Web.config file. By default only WebHttpBinding has been created.so We are suppose to add metadata, in this case it is mexHttpBinding.


  


 


I hope you people like this article.




 

No comments:

Post a Comment