Posting complex types using ASP.NET Ajax, WebForms

27 Jul

This is a minor post, which is some sort of a completion to the previous post dealing with the same topic only for using MVC. So, if you require background, you may want to consider reading that post first.

Fortunately, ASP.NET Ajax makes it really easy to send JSON back and forth. Using jQuery, there is some tweaking that had to be done in order to get this to work. However in WebForms usnig ASP.NET Ajax PageMethods or WebMethods – ASP.NET takes care about the technical details, leaving you to implement only the logic. Note that the same technique and guidelines are used just like in MVC: the data is sent from the Client browser to the Server using POST and in JSON format, with a Content-Type of application/json. All properties must match in data-type and names.

This is the client code:

    <form id="form1" runat="server">
    <asp:ScriptManager runat="server" EnablePageMethods="true" />
    <input type="button" value='click me to test' onclick='Test();' />
    <script type="text/javascript">
        function Test() {
            var data =
                people: [
                    {name: 'Joe', age: 20},
                    {name: 'Jane', age: 30}

            PageMethods.Test(data, function (result){

And the server side, containing classes matching the client type:

    public static void Test(MyPeople data)


    public class MyPeople
        public IEnumerable<Person> People { get; set; }

    public class Person
        public string Name { get; set; }
        public int Age { get; set; }

And the traffic:

As you can see for yourself, this is pretty much straight forward. ASP.NET Ajax client infrastructure takes care to POST the data and send it in JSON format and the appropriate application/json content-type, which is great.

Leave a comment

Posted by on 27/07/2012 in Software Development


Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: