Aspdotnet-Suresh

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

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

Dec 17, 2013
Introduction:

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

Description:

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 asp.net using C#, VB.NET.

Before implement this first create table in your database like this

Column Name
Data Type
Allow Nulls
UserId
Int(Set Identity=true)
No
UserName
VARCHAR(50)
Yes
Role
VARCHAR (50)
Yes
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;

[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
UserDetails[] GetUserDetails(string Username);
}
[DataContract]
public class UserDetails
{
string userid = string.Empty;
string username = string.Empty;
string location = string.Empty;
[DataMember]
public string UserId { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember]
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))
{
con.Open();
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();
da.Fill(dtresult);
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();
userdetails.Add(userInfo);
}
}
con.Close();
}
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


<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndPointBehavior" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndPointBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>

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="http://www.w3.org/1999/xhtml">
<head>
<title>Call WCF Service using jQuery JSON AJax Sample in Asp.net</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
$('#tbDetails').hide();
$('#btnClick').click(function () {
$.ajax({
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>");
}
$('#tbDetails').show();
},
error: function (result) {
alert(result);
}
});

});
});
</script>
<style type="text/css">
table,th,td
{
border:1px solid black;
border-collapse:collapse;
}
</style>
</head>
<body>
<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">
<td>UserId</td>
<td>UserName</td>
<td>Role</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
</body>
</html>

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

Demo


Download Sample Code Attached

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

Get the latest Asp.net, C#.net, 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

13 comments :

Gates Next said...

It is awesome....Thanks.

Irtekaz Ahmed Khan said...

Thanks sir jquery is powerful

Anonymous said...

cool code!

-Jack

Anonymous said...

great!!

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

Thanks...

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 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.