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…
- Create a WCF project
- Add an Ajax Enabled WCF Service to the project.
- Add the following piece of code above your function
[OperationContract]
[WebInvoke(Method = “POST”, BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] - Compile it.
- Create your ASP.NET project
- Add a page to it.
- Now you need to download the latest jQuery from http://jquery.com/ .
- Add the JS file to your page
- Add the below code to your page.
<script type=”text/javascript”>
<!–
$(function() {
$(“#MyTextBoxID”).change(function(e) {
$.ajax({
url: “http://myserver/myservice.svc/MyFunctionTobeCalled”,
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