This post discusses how to develop Windows Communication Foundation (WCF) service using AJAX and without any configuration settings for WCF. This service can be consumed from Javascript. The service uses a special setting in .svc file which automatically enables an AJAX endpoint. |
You can get the AJAX support for WCF through the ScriptManager control.
1. Create a WCF service project in VS 2010
The service contract code as follows
1: // Define a service contract.
2: [ServiceContract(Namespace = "ConfigFreeWCFAjaxService")]
3: public interface ICalculator
4: {
5: [OperationContract]
6: double Add(double n1, double n2);
7: }
Service Implementation code as follows
1: public class CalculatorService : ICalculator
2: {
3: public double Add(double n1, double n2)
4: {
5: return n1 + n2;
6: }
7: }
The SVC file setting as below
1: <%@ServiceHost
2: language="c#"
3: Debug="true"
4: Service="ConfigFreeWCFAjaxService.CalculatorService"
5: Factory="System.ServiceModel.Activation.
WebScriptServiceHostFactory"
6: %>
1: <asp:ScriptManager ID="ScriptManager" runat="server">
2: <Services>
3: <asp:ServiceReference Path="service.svc" />
4: </Services>
5: </asp:ScriptManager>
Calling the service from javascript
<script type="text/javascript">
function makeAJAXCall(){
var n1 = document.getElementById("num1").value;var n2 = document.getElementById("num2").value;
// Instantiate a service proxy
var proxy = new ConfigFreeWCFAjaxService.ICalculator();
// Call correct operation on proxy
proxy.Add(parseFloat(n1), parseFloat(n2), onSuccess, onFail, null);
break;}
</script>
function onSuccess(mathResult){
document.getElementById("result").value = mathResult;}
The <system.ServiceModel> element can be completely removed from the web.config if you configure your service as shown in the above.