Sudheesh Warrier’s Weblog

June 28, 2009

Calling a WCF from jQuery / Ajax. Without using the ASP.NET ScriptManager

Filed under: Uncategorized — Sudheesh Warrier @ 11:08 am
Tags: , , , , ,

From few hours I was trying to call a WCF from a jQuery and Ajax. in an asp.net page.

To my great disappointment, all the examples in the web  showed me how to use a WCF hosted in the same project using ASP.NET Script Manager.

See my bad luck, my WCF was totaling in a different project. None of the examples helped me.

So even being a newbie to Ajax and WCF, I thought to try my own hands in it.

Enough of story let’s do it now…

  1. Create a WCF project
    1. Add an Ajax Enabled WCF Service to the project.
    2. Add the following piece of code above your function
      [OperationContract]
      [WebInvoke(Method = “POST”, BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
    3. Compile it.
    4. Create your ASP.NET project
      1. Add a page to it.
      2. Now you need to download the latest jQuery from http://jquery.com/ .
      3. Add the JS file to your page
      4. Add the below code to your page.

<script type=”text/javascript”>

<!–

$(function() {

$(“#MyTextBoxID”).change(function(e) {

$.ajax({

url: “http://myserver/myservice.svc/MyFunctionTobeCalled&#8221;,

data: ‘{ “ParamaeterNameintheservice”: “ValueFromTheASPPage” }’,

type: “POST”,

processData: false,

contentType: “application/json”,

timeout: 10000,

dataType: “text”,

success: function(data) {

alert(data);

},

error: function(e) {

alert(“Not able to contact the server.”);

}

})

});

});

//–>

</script>

The above example shows how to call the WCF service, from on the change of a textbox value.

Imp: please not the data part in the call. It should be first a single quote, and then inside you have to use the double quotes. (this error spoiled my half an hour.)

Cheers… J

http://atomviews.com/

Advertisements

Create a free website or blog at WordPress.com.