aspdotnet-suresh offers articles and tutorials,csharp dot net, articles and tutorials,VB.NET Articles,Gridview articles,code examples of 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Call WCF Service from jQuery Ajax JSON Example in using C#

Dec 17, 2013

Here I will explain how to call WCF service in jQuery Ajax or JSON example in using C#, VB.NET.


In previous articles explained clearly what WCF (windows communication foundation) is and how to create and consume WCF service in c#(windows application) and I also explained clearly uses of WCF Service. Now I will explain how to call WCF service in jQuery Ajax or JSON example in using C#, VB.NET.

Before implement this first create table in your database like this

Column Name
Data Type
Allow Nulls
Int(Set Identity=true)
After that First open Visual Studio and click file ---> Select New ---> Website Under that select WCF Service and give name for WCF Service and click OK

Once you created application you will get default class files including Service.cs and IService.cs

Here IService.cs is an interface it contains Service contracts and Data Contracts and Service.cs is a normal class inherited by IService where you can all the methods and other stuff.

Now open IService.cs file and write the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

public interface IService
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
UserDetails[] GetUserDetails(string Username);
public class UserDetails
string userid = string.Empty;
string username = string.Empty;
string location = string.Empty;
public string UserId { get; set; }
public string UserName { get; set; }
public string Role { get; set; }

If you observe above code I added WebInvoke attribute it will help us to invoke method for HTTP requests and to represent response data in JSON I declared ResponseFormat

After that open Service.cs and write the following code

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.ServiceModel.Activation;
using System.Data;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
public UserDetails[] GetUserDetails(string Username)
string str = string.Empty;
string strConnection = "Data Source=sureshdasari; Initial Catalog = MySampleDB; User Id=sa; Password=test";
List<UserDetails> userdetails = new List<UserDetails>();
using (SqlConnection con = new SqlConnection(strConnection))
SqlCommand cmd = new SqlCommand("Select TOP 10 UserId,UserName,Role FROM UserDetails WHERE username LIKE '%'+@Name+'%'", con);
cmd.Parameters.AddWithValue("@Name", Username);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtresult = new DataTable();
if (dtresult.Rows.Count > 0)
for (int i = 0; i < dtresult.Rows.Count; i++)
UserDetails userInfo = new UserDetails();
userInfo.UserId = dtresult.Rows[i]["UserId"].ToString();
userInfo.UserName = dtresult.Rows[i]["UserName"].ToString();
userInfo.Role = dtresult.Rows[i]["Role"].ToString();
return userdetails.ToArray();

If you observe above code I added AspNetCompatibilityRequirements attribute that will make our wcf service same as ASMX webservice and able to process requests through HTTP

Now in web.config file we need to write the code like as shown below

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<service name="Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndPointBehavior" />
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<behavior name="EndPointBehavior">
<enableWebScript />

In above code if you observe we changed endpoint behavior to support web HTTP requests and this endpoint settings will work with WebInvoke attribute and AspNetCompatibilityRequirements attribute to support HTTP requests with jQuery.

Now open your Default.aspx page and write the following code

<html xmlns="">
<title>Call WCF Service using jQuery JSON AJax Sample in</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
$(function () {
$('#btnClick').click(function () {
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'Service.svc/GetUserDetails',
data: '{"Username": "' + $("#txtName").val() + '"}',
dataType: "json",
processData: false,
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#tbDetails").append("<tr><td>" + data.d[i].UserId + "</td><td>" + data.d[i].UserName + "</td><td>" + data.d[i].Role + "</td></tr>");
error: function (result) {

<style type="text/css">
border:1px solid black;
<form id="form1" runat="server">
<b>Enter UserName:</b> <input type="text" id="txtName" />
<input type ="button" id="btnClick" value="Get Data" />
<table id="tbDetails" cellpadding="0" cellspacing="0">
<thead style="background-color:#DC5807; color:White; font-weight:bold">
<tr style="border:solid 1px #000000">

Now everything is ready run your application that output should be like this


Download Sample Code Attached

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest,, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email


Gates Next said...

It is awesome....Thanks.

Irtekaz Ahmed Khan said...

Thanks sir jquery is powerful

Anonymous said...

cool code!


Anonymous said...


Anonymous said...

nice work

Unknown said...

simple example, its working fine . thanks for knowledge sharing. :)

Unknown said...

I got the error as method not found

Unknown said...


Anonymous said...

very good example. .thanks

Anonymous said...

Is this code work from cross domain ?

In this example, you are calling service via ajax within same domain, but my services are hosted on different domain . and I want to call those web services via ajax, same way you are calling in this example...

Anonymous said...

This Code Doesn't working on my PC.
my services are hosted on different domain . and I want to call those web services via ajax, same way you are calling in this example

Anonymous said...

i have hosted my service in IIS . when i call through client , the CLIENT"S web.config file is not getting updated . I have searched through net but havn't yet got a proper answer . Any help would be appriciated .Thanks in Advance .

Bhupendra Singh Parihar said...

your code is working fine in Website mode, but when i create same code in Project mode(i.e. right click>new project) then it is not running. i am getting error :http://localhost:53376/bsp.svc/GetUserDetails 415 (Unsupported Media Type)

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.