In this article I will explain with an example, how to return JSON data (object) from WebMethod (PageMethod) in ASP.Net using C# and VB.Net.
In this example, the JSON data (object) will be populated from database and it will be returned by the WebMethod (PageMethod) to jQuery AJAX function.
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
HTML Markup
The following HTML Markup consists of an HTML
DIV with an HTML Table. The HTML table will be used for displaying the returned JSON data (object) from ASP.Net WebMethod (PageMethod).
<div id = "dvCustomers">
<table class="tblCustomer" cellpadding="2" cellspacing="0" border="1">
<tr>
<th>
<b><u><span class="name"></span></u></b>
</th>
</tr>
<tr>
<td>
<b>City: </b><span class="city"></span><br />
<b>Postal Code: </b><span class="postal"></span><br />
<b>Country: </b><span class="country"></span><br />
<b>Phone: </b><span class="phone"></span><br />
<b>Fax: </b><span class="fax"></span><br />
</td>
</tr>
</table>
</div>
Namespaces
You will need to import the following namespaces.
C#
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
VB.Net
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services
The Property Class
The following property class is created to hold the data returned from database and it is returned to the Client Side script as a JSON object.
C#
public class Customer
{
public string CustomerId { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PostalCode { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
}
VB.Net
Public Class Customer
Public Property CustomerId() As String
Public Property ContactName() As String
Public Property City() As String
Public Property Country() As String
Public Property PostalCode() As String
Public Property Phone() As String
Public Property Fax() As String
End Class
WebMethod (PageMethod) returning JSON data (object)
The following WebMethod (PageMethod) will return JSON data (object). When a call is made to the WebMethod (PageMethod), it first fetches the records from the database and populates a Generic list of Customer class objects and then the list is returned as a JSON object back to the Client Side function.
C#
[WebMethod]
public static List<Customer> GetCustomers()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Customers"))
{
cmd.Connection = con;
List<Customer> customers = new List<Customer>();
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new Customer
{
CustomerId = sdr["CustomerId"].ToString(),
ContactName = sdr["ContactName"].ToString(),
City = sdr["City"].ToString(),
Country = sdr["Country"].ToString(),
PostalCode = sdr["PostalCode"].ToString(),
Phone = sdr["Phone"].ToString(),
Fax = sdr["Fax"].ToString(),
});
}
}
con.Close();
return customers;
}
}
}
VB.Net
<WebMethod()> _
Public Shared Function GetCustomers() As List(Of Customer)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT TOP 10 * FROM Customers")
cmd.Connection = con
Dim customers As New List(Of Customer)()
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
customers.Add(New Customer() With { _
.CustomerId = sdr("CustomerId").ToString(), _
.ContactName = sdr("ContactName").ToString(), _
.City = sdr("City").ToString(), _
.Country = sdr("Country").ToString(), _
.PostalCode = sdr("PostalCode").ToString(), _
.Phone = sdr("Phone").ToString(), _
.Fax = sdr("Fax").ToString() _
})
End While
End Using
con.Close()
Return customers
End Using
End Using
End Function
Client Side functionality
Inside the jQuery document ready event handler, an AJAX call is made to the WebMethod (PageMethod). Inside the Success event handler, a loop is executed over the items of the received JSON object.
Inside the loop, the HTML Table is cloned and the columns values are set to their respective fields using the CSS class names.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function OnSuccess(response) {
var table = $("#dvCustomers table").eq(0).clone(true);
var customers = response.d;
$("#dvCustomers table").eq(0).remove();
$(customers).each(function () {
$(".name", table).html(this.ContactName);
$(".city", table).html(this.City);
$(".postal", table).html(this.PostalCode);
$(".country", table).html(this.Country);
$(".phone", table).html(this.Phone);
$(".fax", table).html(this.Fax);
$("#dvCustomers").append(table).append("<br />");
table = $("#dvCustomers table").eq(0).clone(true);
});
}
</script>
Screenshot
Demo
Downloads