您的位置:首页 > 移动开发 > Objective-C

Send and Receive JSON objects to Web Service Methods using jQuery AJAX in ASP.Net

2014-05-20 16:45 1031 查看
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.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐