Hi friends,
In this article you will learn how to call WCF Service using Jquery
But before this article you must know following
- How to Create WCF Service
- How to Host WCF Service
- Jquery Basics
Step 1:
Use of
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
Attribute.
you need to specify the attributes on the server type class for ASP.NET compatibility mode, so that the WCF service works as a normal ASMX service and supports all existing ASP.NET features
eg :
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public string[] GetSupplier(string Id)
{
return new User().GetSupplier (Convert.ToInt32(Id));
}
}
public class User
{
Dictionary<int, string> Supplier = null;
public User()
{
Supplier= new Dictionary<int, string>();
Supplier.Add(1, "Sujeet");
Supplier.Add(2, "Ajay");
Supplier.Add(3, "Sanjay");
Supplier.Add(4, "Amit");
}
public string[] GetUser(int Id)
{
var Supplier = from s in Supplier
where s.Key == Id
select s.Value;
return Supplier.ToArray<string>();
}
}
In the above example I have shown you how to create myService which return names of suppliers.
Step 2:-
Operation contract setting
[OperationContract]
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetSupplier(string Id);
In the above code
ResponseFormat = WebMessageFormat.Json
indicates that data is returned in JSON format.Step 3:- App.config Setting
You have to use weHttp for endpoints
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="webHttpBinding"
contract="IService" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
</system.serviceModel>
Step 4 : Ajax call with Jquery
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: ‘Service.svc/GetSupplier’,
data: parameters,
dataType: "json",
async: true,
success: function (data) {
resultObject = data.GetSupplierResult;
for (i = 0; i < resultObject.length; i++) {
alert(resultObject[i]);
}
});
In this way you can learn Calling WCF Services using jquery
If you have any query mail me to Sujeet.bhujbal@gmail.com
Regards