1

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:

output of serialize

It should be an array of objects with QuestionChoicesId, DisplayText, and OrderNumber for each object.

3 Answers 3

2

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();

DEMO

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

Comments

1

You can use: jquery.serializeToJSON - https://github.com/raphaelm22/jquery.serializeToJSON Its is prepared to work with forms ASP MVC

var obj = $("form").serializeToJSON();

Comments

0

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.

1 Comment

It wasn't mapping correctly in the controller. Kept yelling about NullReferenceException. So, I tracked the problem to the incorrect serialization of my form <div>.

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.