Call WCF Service from jQuery Ajax JSON Example in Asp.net using C#
Categories: Asp.net , C#.Net , JQuery , WCF
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>
No comments:
Post a Comment
Hello all, if you have any doubt feel free comment