странная проблема при передаче объекта JSON в метод c # (с коллекцией в качестве параметра (с использованием JQuery Widgets) - PullRequest
2 голосов
/ 06 января 2012

Я сталкиваюсь со странной проблемой при передаче следующего:

queueNotificationData = {
            StartDate: that.batchData.StartDate.valueOf(),
            StartTime: that.batchData.StartTime.valueOf(),
            EndDate: that.batchData.EndDate.valueOf(),
            EndTime: that.batchData.EndTime.valueOf(),
            ETR: that.batchData.ETR.valueOf(),
            PTW: that.batchData.PTW.valueOf(),
            SelectedTemplate: that.batchData.SelectedTemplate.valueOf(),
            IncidentFlag: that.batchData.IncidentFlag.valueOf(),
            IncidentNumber: that.batchData.IncidentNumber.valueOf(),
            SendToSubscriber: that.batchData.SendToSubscriber.valueOf(),
            SendToCustomer: that.batchData.SendToCustomer.valueOf(),
            SendToSMC: that.batchData.SendToSMC.valueOf(),
            BatchServiceIds: that.serviceIds,
            DescriptionOfWorks: that.batchData.DescriptionOfWorks.valueOf(),
            AffectedCustomerVOs: that.customerVOs
        }

Проблема связана с параметром ActedCustomerVOs - он извлекается из более раннего вызова и передается через серию виджетов (это частьдовольно длинной формы мастера)

Это код, вызывающий метод c # для фактической обработки:

this.options.sendRequest({
                url: this.options.dataUrl,
                data: queueNotificationData,
                cache: false,
                dataType: 'json',
                success: function (data) {
                    that.data = data;
                    that._showSavedMessage();
                },
                error: function () {
                    that._showErrorMessage();
                }
            });

, а вот метод c #:

    [HttpPost]
    [Authorize]
    [ValidateInput(false)]
    public JsonResult QueueNotificationBatch(QueueNotificationInputModel param)
    {
         //do some work - code not included
    }

где QueueNotificationInputModel равен

public class QueueNotificationInputModel
{
    public string BatchServiceIds { get; set; }
    public List<CustomerVO> AffectedCustomerVOs { get; set; }
    public string StartDate { get; set; }
    public string StartTime { get; set; }
    public string EndDate { get; set; }
    public string EndTime { get; set; }
    public string ETR { get; set; }
    public string PTW { get; set; }
    public string SelectedTemplate { get; set; }
    public string IncidentFlag { get; set; }
    public string IncidentNumber { get; set; }
    public bool SendToSubscriber { get; set; }
    public bool SendToCustomer { get; set; }
    public bool SendToSMC { get; set; }
    public string DescriptionOfWorks { get; set; }

    public QueueNotificationInputModel()
    {
        AffectedCustomerVOs = new List<CustomerVO>();
    }
}

Теперь - кажется, что весь этот код работает нормально - метод C # успешно вызывается, а значения, переданные ему, хороши, за исключением ActedCustomerVO.В списке есть 3 элемента (это правильно), но элементы в списке не имеют значений - все нули / 0.Если я поставлю оповещение (that.customerVOs [0] ['Email']);непосредственно перед созданием объекта queueNotificationData он правильно отображает «test@test.com», но это значение никогда не попадает в метод c #.

Я предполагаю, что это какая-то проблема с сериализацией, но я не могу понять где?Помощь будет высоко ценится

1 Ответ

1 голос
/ 06 января 2012

Попробуйте отправить этот сложный объект как сериализованный JSON:

this.options.sendRequest({
    url: this.options.dataUrl,
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(queueNotificationData),
    cache: false,
    dataType: 'json',
    success: function (data) {
        that.data = data;
        that._showSavedMessage();
    },
    error: function () {
        that._showErrorMessage();
    }
});

Показанный здесь метод JSON.stringify изначально встроен в современные браузеры. Если вам нужна поддержка устаревших браузеров, вам может потребоваться включить скрипт json2.js на свою страницу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...