Reputation: 379
I'm having a problem passing an associative array of objects to MVC Controller. I always get null
.
This is what I have on client-side:
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;
}
I have an array 'items' and is filled like this:
items['i123'] = new Item();
On the server-side I mapped that:
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; }
}
My MVC Controller method is this:
[HttpPost]
public ActionResult Create(int userId, string userHash, EvItemJs[] items)
On the client-side I call the MVC Controller with this:
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) {
}
});
The userId and userHash parameters have correct values, but the items is always null.
Anyone knows what is wrong? I tried with JSON.stringify
and $.toJSON
. I remember that sometime I did this with serialization but I cant find it.
Edit: this is what the browser sends to the server:
Upvotes: 3
Views: 1178
Reputation: 379
i solved it converting the associative array to non-associative:
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;
}
Thanks to everybody!
Upvotes: 1