3

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"
    }
  ]
}"
9
  • Maybe I'm missing something, but I don't see you ever touching Questions and Items in your JS. What happens if you use question and item instead of Questions and Items Commented Feb 4, 2013 at 17:26
  • Apologies, left something out, i'll edit now Commented Feb 4, 2013 at 17:29
  • I'm not sure that jQuery will actually convert the data to JSON when you specify contentType: "application/json". Have you checked the data being transmitted? Commented Feb 4, 2013 at 17:40
  • @Barmar I have confirmed that the id and response-id are being transmitted to the controller correctly with and without contentType: "application/json. It's the IEnumerable values that has me stumped. No matter what I do i get nothing but Null values Commented Feb 4, 2013 at 17:42
  • 2
    If you want a neater "dump" of your data object, open the console in your debugger and run this: JSON.stringify(data, null, 2). Commented Feb 4, 2013 at 18:01

2 Answers 2

3

You want to serialize your array to JSON using JSON.stringify
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

1) install Json.net in Nuget to include the JsonFilter notation

PM> Install-Package Newtonsoft.Json

2) place a Json Filter annotation on your action method

[JsonFilter(Param = "attributes", JsonDataType = typeof(AttributeViewModel[]))]
  JsonResult SubmitResponseScores(SubmitResponseScoresViewModel model)

3) In your ajax call:

    data:  JSON.stringify(data), 
Sign up to request clarification or add additional context in comments.

Comments

0

Your collections for Questions and Items need to be public else they will not be bound to the model on post-back

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.