JQuery post () with serialization and data array

I cannot get the value of the collection at the time of publication in mvc 3. it returns 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); 
+4
source share
4 answers
  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 }); 
+2
source

I had a similar problem while passing arrays.

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

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

Important traditional: true option traditional: true

+7
source

For several months I banged my head against this wall with the usual .ajax () call.

In the end, I found out that you need to set traditional: true to the parameter list for $ .ajax (). (see here the "traditional" header: http://api.jquery.com/jQuery.ajax/ )

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

+3
source

The following worked for me. You can use serializeArray () serializeJSON () as shown below and set this for the data item. Note the variable formData strong>.

 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."); } }); 
-1
source

All Articles