Simplest Tutorial for AJAX, JQUERY, WebMethod Call returning JSON

Code Behind

[codesyntax lang=”vbnet”]

Imports System.Web.Services
Imports System.Web.Script.Services

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService> _
Partial Class _Default
Inherits System.Web.UI.Page
<WebMethod()> _
Public Shared Function ReturnJSONData() As Person
Dim guy As New Person
guy.Name1 = "Joe"
guy.Age = 8
Return guy
End Function
End Class

Public Class Person
Private _name As String
Public Property Name1() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _age As Int32
Public Property Age() As Int32
Get
Return _age
End Get
Set(ByVal value As Int32)
_age = value
End Set
End Property
End Class

[/codesyntax]

 

ASPX Page

[codesyntax lang=”html4strict”]

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <form id="form1" runat="server">
        <a href="#" id="Result">Click for Call</a>
    </form>
</body>
<script>
    $(document).ready(function () {
            // Add the page method call as an onclick handler for the div.
            $("#Result").click(function () {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/ReturnJSONData",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        // Replace the div's content with the page method's return.
                        alert(msg.d.Name1 + ':' + msg.d.Age);
                    }
                });
            });
    });
</script>
</html>

[/codesyntax]

Author: Travis Gneiting

Passionate Professional .NET Developer