Reputation: 1324
I am trying to serialize all inputs in a specific form into an object array so that I can pass it to my controller action and then update multiple rows at once. My issue is the serializing part... It's messing up somehow.
Here is where I generate the form:
$.each(content, function (i, item) {
var html = "<br />Choice ID<br /><input type='text' name='QuestionChoicesId' value='"
+ item.QuestionChoicesId + "'><br />Choice Display Text<br /><input type='text' name='DisplayText' value='"
+ item.DisplayText + "'><br />Order of Display<br /><input type='text' name='OrderNumber' value='"
+ item.OrderNumber
+ "'>";
$(html).appendTo("#choices");
});
This is what i am trying to do:
console.log($('#choices :input').serializeArray());
$.ajax({
type: "POST",
url: "/Question/UpdateQuestionchoices/",
data: $('#choices :input').serialize()
});
Here is the console.log
output:
It should be an array of objects with QuestionChoicesId
, DisplayText
, and OrderNumber
for each object.
Upvotes: 1
Views: 1370
Reputation: 61
You can use: jquery.serializeToJSON - https://github.com/raphaelm22/jquery.serializeToJSON Its is prepared to work with forms ASP MVC
var obj = $("form").serializeToJSON();
Upvotes: 1
Reputation: 343
Although it may be structured like that, I think it posts as you would expect. Did you look at how it was posted in the ajax call? I have done the same thing and it worked as expected and bound correctly.
Upvotes: 0
Reputation: 171679
First would suggest you wrap each group, so a loop can be built over the wrappers
$.each(content, function (i, item) {
var html = '<div class="control_group">';
/* your exisiting string build code*/
html += '</div>';
});
To create array:
var ajaxData = $('.control_group').map(function (idx,group) {
var data = {};
$(group).find(':input').each(function () {
data[this.name] = this.value;
});
return data;
}).get();
Upvotes: 2