We can return any type of data from web service and we can return generic list also. If we need to consume web service using jQuery and we need to get this generic list data from web service then we can do it easily. I will create a Products class and write a method to get data from Products table of NORTHWND database. I will return a list of Products class in WebMethod and will write client side code using jQuery in aspx page to handle and display products in between a div tag.
1.Open Visual Studio 2010
2.File > New > Web Site
3.Visual Basic or Visual C# > ASP.NET Empty Web Site
4.Right click on web site > Add New Item > Web Form
5.Right click on website > New Folder (Name the folder as “Scripts”). Download jQuery and jQuery autocomplete plug-in and include below files in this folder.
jquery-1.4.1.min.js
6.Add a tag in between tag of Default.aspx page. You have to give reference for jQuery as below.
<head runat="server">
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
</head>
7.Right click on web site > Add New Item > Web Service
8.Add a code below in WebService.asmx
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
///
/// Summary description for WebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public List GetProducts()
{
DataTable table = ProductsData();
List list = new List();
foreach (DataRow row in table.Rows)
{
Products detail = new Products();
detail.ProductID = Convert.ToInt32(row["ProductID"]);
detail.ProductName = row["ProductName"].ToString();
detail.CategoryID = Convert.ToInt32(row["CategoryID"]);
detail.UnitPrice = Convert.ToDecimal(row["UnitPrice"]);
list.Add(detail);
}
return list;
}
private DataTable ProductsData()
{
string cmdText = "SELECT ProductID, ProductName, CategoryID, UnitPrice FROM Products WHERE UnitPrice <= 10";
string myConnection = "Data Source=DEV01-PC;AttachDbFilename=C:\\SQL Server 2000 Sample Databases\\NORTHWND.MDF;Initial Catalog=NORTHWND;Integrated Security=True";
SqlConnection connection = new SqlConnection(myConnection);
SqlCommand command = new SqlCommand(cmdText, connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable table = new DataTable();
adapter.Fill(table);
connection.Close();
return table;
}
}
public class Products
{
private int prodID = 0;
private string prodName = "";
private int catID = 0;
private decimal unitPrice = 0;
public int ProductID
{
set
{
this.prodID = value;
}
get
{
return this.prodID;
}
}
public string ProductName
{
set
{
this.prodName = value;
}
get
{
return this.prodName;
}
}
public int CategoryID
{
set
{
this.catID = value;
}
get
{
return this.catID;
}
}
public decimal UnitPrice
{
set
{
this.unitPrice = value;
}
get
{
return this.unitPrice;
}
}
}
VB.NET
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data
Imports System.Data.SqlClient
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetProducts() As List(Of Products)
Dim table As DataTable = ProductsData()
Dim list As New List(Of Products)()
For Each row As DataRow In table.Rows
Dim detail As New Products()
detail.ProductID = Convert.ToInt32(row("ProductID"))
detail.ProductName = row("ProductName").ToString()
detail.CategoryID = Convert.ToInt32(row("CategoryID"))
detail.UnitPrice = Convert.ToDecimal(row("UnitPrice"))
list.Add(detail)
Next
Return list
End Function
Private Function ProductsData() As DataTable
Dim cmdText As String = "SELECT ProductID, ProductName, CategoryID, UnitPrice FROM Products WHERE UnitPrice <= 10"
Dim myConnection As String = "Data Source=DEV01-PC;AttachDbFilename=C:\SQL Server 2000 Sample Databases\NORTHWND.MDF;Initial Catalog=NORTHWND;Integrated Security=True"
Dim connection As New SqlConnection(myConnection)
Dim command As New SqlCommand(cmdText, connection)
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
connection.Close()
Return table
End Function
End Class
Public Class Products
Private prodID As Integer = 0
Private prodName As String = ""
Private catID As Integer = 0
Private m_unitPrice As Decimal = 0
Public Property ProductID() As Integer
Get
Return Me.prodID
End Get
Set(value As Integer)
Me.prodID = value
End Set
End Property
Public Property ProductName() As String
Get
Return Me.prodName
End Get
Set(value As String)
Me.prodName = value
End Set
End Property
Public Property CategoryID() As Integer
Get
Return Me.catID
End Get
Set(value As Integer)
Me.catID = value
End Set
End Property
Public Property UnitPrice() As Decimal
Get
Return Me.m_unitPrice
End Get
Set(value As Decimal)
Me.m_unitPrice = value
End Set
End Property
End Class
I have created a class Products and get and set properties for ProductID, ProductName, CategoryID and UnitPrice. Then I have written a function which returns a DataTable of all these fields of Products table. In WebMethod, I have created a list object of Products class and added all the values to the list and this WebMethed returns list of Products class.
9.Now write code below in Default.aspx page
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "WebService.asmx/GetProducts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var prods = r.d;
$.each(prods, function (index, prod) {
$("#div1").append("<strong>" + prod.ProductName + "</strong>" + "<br/>" +
"ProductID: " + prod.ProductID + "<br />" +
"CategoryID: " + prod.CategoryID + "<br />" +
"UnitPrice: " + prod.UnitPrice + "<br />");
});
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Display Products" />
<div id="div1">
</div>
</div>
</form>
</body>
</html>
I have added an input field of type Button and a div tag in between form tag. In between head tag, I have written jQuery code to call the GetProducts function of Web Service. In success function, I have displayed data in div tag for each list item.
10.Now you can see it in your browser