Mitten
Mitten

Reputation: 249

How to call WCF service using jQuery ajax functions

I created simple WCF service and added it to ASP.NET MVC application.

The service have a single method RepeatString:

[OperationContract]
public string RepeatString(string s, int times)
{
   string result = "";

   for (int i = 0; i < times; ++i)
   {
       result += s;
   }


   return result;
}

I tried to call this method from a view (.cshtml) using post and get methods:

function callAjaxService1() {    
    $.post("~/AjaxService1.svc/RepeatString", {s : 'Test', times : 12},
        function(data) {
            alert('data from service');
        }, 'json');
}

function callAjaxService1() {    
    $.get("~/AjaxService1.svc/RepeatString", {s : 'Test', times : 12},
        function(data) {
            alert('data from service');
        }, 'json');
}

but neither has succeed.

Is there anything I should change in WCF service operation decoration or am I using jQuery.get/post wrongly?

Upvotes: 2

Views: 6359

Answers (2)

photowalker
photowalker

Reputation: 373

I would think of something like this...

wcf interface service

[OperationContract]
[WebGet(UriTemplate = "/repeatstring",
ResponseFormat= WebMessageFormat.Json)]
string RepeatString(string s, int times);

Then your code

public string RepeatString(string s, int times)
{
   string result = "";

   for (int i = 0; i < times; ++i)
   {
       result += s;
   }


   return result;
}

without the operationcontract but the page will be derived from the interface so your ajax code would be something like this.

$.ajax({
  type: "GET", //to get your data from the wcf service
  url: "AjaxService1.svc/repeatstring", //you might need to add the hostname at the beginning too
  data: option // or { propertyname1: "John", propertyname2: "Boston" }
})
  .done(function() {
    alert( "got data" );
  });

you can add more options to the $.ajax. You can change the "done" promise to "success" which will do work when the operation is a success. I used success when i created my wcf services and needed to send data wich json and get it with javascript. anyways you can read more about it on here

be aware of the single ' and dubble " quote marks when writing a json string or the "option" variabel

Now I hope this would help you somehow. Cheers

Upvotes: 1

Saranya
Saranya

Reputation: 2008

Three things are to be taken care for a WCF to be invoked from javascript.

  1. The Service has to be decorated with WebInvoke/WebGet to be accessed from javascript.

  2. <enableWebScript/> has to be added to the configuration for enabling script calls to WCF.

  3. webHttpBinding is to be used for the WCF to behave as a REST service.

Upvotes: 0

Related Questions