5

i am unable to get collection value during post in mvc 3. it is returning null.

$.post("/Work/Post", { vm: $('#myForm').serializeArray(), 'collection': ['a', 'b', 'c'] });

//Or


var data = $('#myForm').serializeArray();
data.push({ name: 'collection', value: ['a', 'b', 'c'] });
$.post("/Work/Post", data);

//Or

var data = $('#myForm').serializeArray();
data.push({ name: 'collection[]', value: ['a', 'b', 'c'] });
$.post("/Work/Post", data);
2
  • Try using .ajax directly rather than .post and see if you get something Commented Aug 8, 2012 at 15:34
  • Use Firebug, or a similar tool, to see what data is being sent as part of the request, and check that it matches the format you're expecting/needing it to be on the server. Commented Aug 8, 2012 at 15:36

4 Answers 4

8

I had a similar problem when passing arrays.

Instead of using $.post use $.ajax and set the traditional option = true ...

$.ajax({
    type: "POST",
    url: "Work/",
    traditional: true,
    data: { collection: ['a','b','c'] }
});

The traditional: true option is important

Sign up to request clarification or add additional context in comments.

Comments

4
                var model = $('#myForm').serializeArray();

                $.map(['a', 'b', 'c'], function (val, i) {
                    return model.push({ "name": "collection[" + i + "]", "value": val });
                });

                $.post("/Work/Post", model);
                //OR
                $.post("/Work/Post", model, function (data) {
                    //After Success
                });

1 Comment

More people should know the name value pair usage of jquery ajax data model.
3

I banged my head against this wall for months with the regular .ajax() call.

I eventually found out that you need to set traditional: true in the params list for $.ajax(). (see the "traditional" heading here: http://api.jquery.com/jQuery.ajax/)

Since there is no params list for $.post(), I'm not sure you can do this with $.post(). But it's not much more code to use $.ajax().

Comments

-1

The following worked for me. You can use serializeArray() serializeJSON() as below and set that to the data element. Observe the formData variable.

var formData = $('#inputForm').serializeJSON();
$.ajax({
    type : "POST",
    url: server_side_url,
    cache:false,
    traditional: true,
    data: formData,
    dataType: "json",
    success: function(data, textStatus, jqXHR){
        console.log("successfully processed.");
    },
    error: function(xhr,status,error){
        console.log("error occurred.");
    }
}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.