I'm having a huge amount of trouble passing a Javascript array to my controller in MVC 3. I keep getting null values and feel like I have tried every way of passing the array. Below is the JavaScript, the relevant view models for the Questions and the controller signature. I'd appreciate any help. I'm not getting any errors in my JavaScript and I think i must be missing something fundamental.
The values for id and response-id are being received correctly at the controller.
javascript
$("#form-submit-scores").submit(function () {
var question = [],
var item = [],
$('.questionRow').each(function (index) {
question[index] = new Array();
var fullQuestionId = $(this).attr('id');
var fullQuestionParts = fullQuestionId.split('-');
question[index].QuestionId = fullQuestionParts[fullQuestionParts.length - 1];
question[index].QuestionScore = $('.scoreBoard').val();
});
$('.itemRow').each(function (index) {
item[index] = new Array();
item[index].ItemId = $(this).attr('id');
item[index].ItemScore = $('.scoreBoard').val();
});
var url = "/ctr/SaveResponse",
data = {
Id: $('#id').val(),
ResponseId: $('#response-id').val(),
Questions: question,
Items : item
},
if (isSubmitScores) {
url = "/ctr/SubmitResponse"
}
$.ajax({
url: url,
type: 'Post',
data: data,
traditional:true,
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
if (!result.Success) {
....
....
....
viewmodels
public class SubmitResponseViewModel
{
public int Id { get; set; }
public int ResponseId { get; set; }
IEnumerable<SubmitResponseScoresQuestionViewModel> Questions {get;set;}
IEnumerable<SubmitResponseScoresItemViewModel> Items { get; set; }
}
public class SubmitResponseScoresQuestionViewModel
{
public int QuestionId { get; set; }
public decimal? QuestionScore { get; set; }
}
controller signature
public JsonResult SubmitResponseScores(SubmitResponseScoresViewModel model)
So as I said above, my model now contains the correct values for Id and response-id but null values for Questions and Items. I have confirmed that my data is being populated in the AJAX call so i'm thinking that I'm not providing the data in the appropriate format for the controller.
EDIT:1
Chrome JS Debugger: AJAX Data object
JSON.stringify(data, null, 2)
"{
"Id": "1027",
"ResponseId": "26",
"Questions": [
{
"QuestionId": "7",
"QuestionScore": "0"
},
{
"QuestionId": "2",
"QuestionScore": "0"
},
{
"QuestionId": "1",
"QuestionScore": "0"
}
],
"Items": [
{
"ItemId": "434",
"ItemScore": "0"
}
]
}"
QuestionsandItemsin your JS. What happens if you usequestionanditeminstead ofQuestionsandItemscontentType: "application/json". Have you checked the data being transmitted?idandresponse-idare being transmitted to the controller correctly with and withoutcontentType: "application/json. It's theIEnumerablevalues that has me stumped. No matter what I do i get nothing but Null valuesdataobject, open the console in your debugger and run this:JSON.stringify(data, null, 2).