JSON serializing of complex object MVC3

2019-04-30 01:15发布

问题:

I have a problem, I don't seem to know how to serialize a object of type:

public class SchedulingCalendarMonth
{
    public List<SchedulingCalendarWeek> Weeks {get; set; }
}
public class SchedulingCalendarWeek
{
    public List<SchedulingCalendarDay> Days { get; set; }
}

public class SchedulingCalendarDay
{
    public int Id { get; set; }
    public bool SomeBoolProperty { get; set; }
}

I've tried something like this:

<script type="text/javascript">

$(document).ready(function () {

    var Month =
    {
        Weeks: []
    };
    var Weeks = { Days: [{ Id: 1, SomeBoolProperty: true }, { Id: 4, SomeBoolProperty: true }, { Id: 43, SomeBoolProperty: false}] };

    Month.Weeks = Weeks;

    $.ajax({
        url: '/Home/Test',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({ month: Month }),
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
            alert(result.Result);
        }
    });
});

But all i get on the controller action is Month object with Weeks = null.

Any ideas?

回答1:

The reason is your Month.Weeks is an array so in order to add one to it, you can't just do it like the above Month.Weeks = Weeks; but rather Month.Weeks.push(Weeks); Give it a go.

Thanks.