1

我正在尝试将一组对象从我的视图传递给我的控制器。然而,每个对象只包含空值。我被困住了。

我的 C# 类:

 public class CalendarColor
    {
        public string BackgroundColor { get; set; }
        public string BorderColor { get; set; }
        public string ItemType { get; set; }
        public string LocationId { get; set; }
        public string TextColor { get; set; }
    }

我在控制器中的方法:

    [HttpPost]
    public ActionResult SaveColors(IEnumerable<CalendarColor> calendarColors)
    {
        do the stuff
    }

这是javascript:

        //The Array that will hold the CalendarColorObjects 
        var calendarColors = [];

        //Loop through the table with the settings 
        $('#tblColorSettings > tbody  > tr').each(function () {
            var calendarColor = {};
            calendarColor.ItemType = $(this).find('td:first').text().trim();
            calendarColor.LocationId = $(this).attr('data-location');
            calendarColor.BackgroundColor = $(this).find('td:nth(1)').find('input').val();
            calendarColor.BorderColor = $(this).find('td:nth(2)').find('input').val();
            calendarColor.TextColor = $(this).find('td:nth(3)').find('input').val();

            //Add to the Array
            calendarColors.push({ CalendarColor : calendarColor });
        });

        var urlSaveSettings = '/settings/savecolors';
        var calendarColorsToBeSaved = { calendarColors: calendarColors };

        $.ajax({
            type: 'POST',
            url: urlSaveSettings,
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(calendarColorsToBeSaved),
            success: function (serverMessage) {
                if (serverMessage == "OK") {
                    alert('OK');
                }
            },

            error: function (msg) {
                alert(msg);
            }
        });

我在控制器方法中得到一组空对象。我似乎无法找出问题所在。

JSON看起来像这样:

{"calendarColors":[{"CalendarColor":{"ItemType":"Booking","LocationId":"1","BackgroundColor":"#464646","BorderColor":"#FFFFFF","TextColor": "#7c541b"}},{"CalendarColor":{"ItemType":"Booking","LocationId":"3","BackgroundColor":"#464646","BorderColor":"#FFFFFF"

...

","BackgroundColor":"#ff9b99","BorderColor":"#000000","TextColor":"#ff5a56"}}]}

4

1 回答 1

1

问题可能是您将对象封装在数组中:

//Loop through the table with the settings 
        $('#tblColorSettings > tbody  > tr').each(function () {
            var calendarColor = {};
            calendarColor.ItemType = $(this).find('td:first').text().trim();
            calendarColor.LocationId = $(this).attr('data-location');
            calendarColor.BackgroundColor = $(this).find('td:nth(1)').find('input').val();
            calendarColor.BorderColor = $(this).find('td:nth(2)').find('input').val();
            calendarColor.TextColor = $(this).find('td:nth(3)').find('input').val();

            //just add the objects to the array
            calendarColors.push(calendarColor);
        });

我只发布了需要更改的代码。

于 2013-04-07T18:01:59.150 回答