WCF service for AJAX

WCF service for client AJAX call returning JSON

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
// Your code comes here
}

[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method = GET”,
ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);

[OperationContract]
[WebInvoke(Method = POST”,
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
}

<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>

Client code with JQuery:

function CallService() {
$.ajax({
type: POST”, //GET or POST or PUT or DELETE verb
url: Service.svc/GetUser”, // Location of the service
data: {“Id”: “‘ + userid + “}’, //Data sent to server
contentType: application/json; charset=utf-8″, // content type sent to server
dataType: json”, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) {ServiceSucceeded(msg);},
error: ServiceFailed// When Service call fails
});

function ServiceSucceeded(result) {
if (DataType == json”) {
resultObject = result.GetUserResult;

for (i = 0; i < resultObject.length; i++) {
alert(resultObject[i]);
}

}
}

function ServiceFailed(result) {
alert(Service call failed: ‘ + result.status + + result.statusText);
Type = null;
varUrl = null;
Data = null;
ContentType = null;
DataType = null;
ProcessData = null;
}

Advertisements

%d bloggers like this: