我在将对象的关联数组传递给 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 Controller 方法是这样的:
[HttpPost]
public ActionResult Create(int userId, string userHash, EvItemJs[] items)
在客户端,我用这个调用 MVC Controller :
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
。我记得有一次我用序列化做了这个,但我找不到它。
编辑:这是浏览器发送给服务器的内容:
最佳答案
我解决了将关联数组转换为非关联数组的问题:
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;
}
谢谢大家!
关于c# - 传递对象的关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21660375/