In this article I will explain with an example, how to send and receive
JSON objects to
Web Service Methods using jQuery AJAX in
ASP.Net.
Custom Object Class
The custom object class consists of following properties.
C#
public class City
{
public string Name { get; set; }
public int Population { get; set; }
}
VB.Net
Public Class City
Public Property Name As String
Public Property Population As Integer
End Class
HTML Markup
Here 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).
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="btnCity" value="Get City" />
</div>
</form>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnCity").click(function () {
var city = {};
city.Name = "Mumbai";
city.Population = 2000;
$.ajax({
type: 'POST',
url: 'CS.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>
</body>
</html>
Server side code
Below I have described the
Web Methods that will process the requests received by the
jQuery AJAX call.
The Web Methods simply accept the object of class City and simply return it back to the client.
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
Screenshot
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