In this article I will explain how to send and receive JavaScript JSON objects to Web Methods using jQuery AJAX in ASP.Net.
Custom Object Class
First I’ll create a simple property class of City which has two simple properties
1. Name – Name of the City
2. Population – Population of the City.
This class will act as the JSON object for sending and receiving date between the client and server.
C#
public class City
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private int population;
public int Population
{
get
{
return population;
}
set
{
population = value;
}
}
}
VB.Net
Public Class City
Private _name As String
Public Property Name As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _population As Integer
Public Property Population As Integer
Get
Return _population
End Get
Set(ByVal value As Integer)
_population = value
End Set
End Property
End Class
HTML Markup
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$("#btnCity").live("click", function () {
var city = {};
city.Name = "Mumbai";
city.Population = 2000;
$.ajax({
type: 'POST',
url: 'MyPage.aspx/GetCity',
data: "{city:" + JSON.stringify(city) + "}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (r) {
alert(r.d.Name);
alert(r.d.Population);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id = "btnCity" value="Get City" />
</div>
</form>
</body>
</html>
Above you will notice that on the click event of the HTML button btnCity I am making a jQuery AJAX call to the ASP.Net WebMethod GetCity which accepts a custom JSON object City with 2 properties (Name and Population). This function also returns a JSON object of type City with the same 2 properties (Name and Population).
Server side code
Below I have described the Web Methods that will process the requests received by the jQuery AJAX call.
C#
[System.Web.Services.WebMethod]
public static City GetCity(City city)
{
return city;
}
VB.Net
<System.Web.Services.WebMethod()> _
Public Shared Function GetCity(ByVal city As City) As City
Return city
End Function
The above Web Methods simply accept the object of class City and simply return it back to the client.
Screenshots
The below screenshot displays how the JavaScript JSON object sent to the server via jQuery AJAX is received by the server side web method.
The below screenshot displays how the JavaScript JSON object is received from the server via jQuery AJAX success event handler.
Downloads
You can download the complete working source code in C# and VB.Net using the download link provided below.
Download Code