Tuesday, May 17, 2011

Pass complex objects from jQuery to ASP.NET MVC controller method

For some reason this doesn't work even when including traditional

$('#Complex').click(function () {

    var y = [];

    for (i = 0; i < 3; ++i) {
        var x = new Object();
        x.MemberName = "George" + i;
        x.BestSong = "Something" + i;
        x.BirthYear = 1943 + i;
        y.push(x);
    }


    var band = { BandName: 'Beatles', Members: y };


    $.ajax({
        url: '/Home/Complex/',
        type: 'POST',
        traditional: true,
        data: band,                
        dataType: 'json',
        success: function (data) {
            alert(data.BandName);
            alert(data.Members.length);
            for (i = 0; i < data.Members.length; ++i) {
                var m = data.Members[i];
                alert(m.MemberName + ' / ' + m.BestSong + ' / ' + m.BirthYear);
            }
        }
    });

});
But this one works:
$('#Complex').click(function () {

    var y = [];

    for (i = 0; i < 3; ++i) {
        var x = new Object();
        x.MemberName = "George" + i;
        x.BestSong = "Something" + i;
        x.BirthYear = 1943 + i;
        y.push(x);
    }


    var band = { BandName: 'Beatles', Members: y };


    var json = JSON.stringify(band);



    $.ajax({
        url: '/Home/Complex/',
        type: 'POST',                

        contentType: 'application/json; charset=utf-8',
        data: json,

        dataType: 'json',
        success: function (data) {
            alert(data.BandName);
            alert(data.Members.length);
            for (i = 0; i < data.Members.length; ++i) {
                var m = data.Members[i];
                alert(m.MemberName + ' / ' + m.BestSong + ' / ' + m.BirthYear);
            }
        }
    });

});
The Controller:
[HttpPost]
public JsonResult Complex(Rockband b)
{
    return Json(b);
}
The Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace JquerySendBatch.Models
{
    public class Rockband
    {
        public string BandName { get; set; }
        public IList<Member> Members { get; set; }
    }

    public class Member
    {
        public string MemberName { get; set; }
        public string BestSong { get; set; }
        public int BirthYear { get; set; }
    }
}

1 comment:

  1. Many thanks for the tip! It really gave the right direction to go on but I had to do some additional things though. For MVC2 apps this approach wouldn't work as is and requires MVC futures to be referenced. For more info,i'd recommend the following article:
    http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

    ReplyDelete