传递关联的对象数组

时间:2014-02-09 14:36:01

标签: c# asp.net-mvc arrays associative

我在将关联对象数组传递给MVC Controller时遇到问题。我总是得到null

这就是我在客户端所拥有的:

function Item() {   
    this.ItemId = GetRandomId('i');
    this.Title = '';
    this.Questions = [];
}

function Question() {
    this.QuestionId = GetRandomId('q');
    this.Description = '';
    this.Values = [];
}

function QuestionValue() {
    this.ValueId = GetRandomId('v');
    this.Description = '';
    this.IsCorrect = false;
}

我有一个数组'items'并且填充如下:

items['i123'] = new Item();

在服务器端,我映射了:

public class EvItemJs
{
    public int ItemId { get; set; }
    public string Title { get; set; }
    public EvQuestionJs[] Questions { get; set; }
}

public class EvQuestionJs
{
    public int QuestionId { get; set; }
    public string Description { get; set; }
    public EvQuestionValueJs[] Values { get; set; }
}

public class EvQuestionValueJs
{
    public int ValueId { get; set; }
    public string Description { get; set; }
    public string IsCorrect { get; set; }
}

我的MVC控制器方法是:

[HttpPost]
public ActionResult Create(int userId, string userHash, EvItemJs[] items)

在客户端,我用这个调用MVC控制器:

var data = { userId: global_data.userId, userHash: global_data.userHash, items: items };

$.ajax({
    url: '/Evaluations/Create',
    type: "POST",
    data: JSON.stringify(data),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    async: true,
    cache: false,
    success: function (msg) {

    },
    error: function (data, ajaxOptions, thrownError) {

    }
});

userId和userHash参数具有正确的值,但这些项始终为null。

任何人都知道出了什么问题?我尝试使用JSON.stringify$.toJSON。我记得有时我用序列化做了这个,但我找不到它。

编辑:这是浏览器发送到服务器的内容:

what the browser sends to the server

1 个答案:

答案 0 :(得分:0)

我解决了它将关联数组转换为非关联数组的问题:

function NormalizeItemsArray() {
    var result = new Array();

    for (var i in items) {
        i = items[i];
        var item = new Item();
        item.ItemId = i.ItemId;
        item.Title = i.Title;
        item.Questions = new Array();

        for (var q in i.Questions) {
            q = i.Questions[q];
            var question = new Question();
            question.QuestionId = q.QuestionId;
            question.Description = q.Description;
            question.Values = new Array();

            for (var v in q.Values) {
                v = q.Values[v];
                var questionValue = new QuestionValue();
                questionValue.ValueId = v.ValueId;
                questionValue.Description = v.Description;
                questionValue.IsCorrect = v.IsCorrect;

                question.Values.push(questionValue);
            }
            item.Questions.push(question);
        }
        result.push(item);
    }

    return result;
}

感谢大家!