jquery ajax form collection and other key/value pairs

Christopher Johnson picture Christopher Johnson · Sep 13, 2011 · Viewed 7.6k times · Source

well since I never got an answer to my question here: checkboxes and radio buttons in MVC FormCollection

I thought I'd take a different approach and just find my radio button value client side, and pass it as a different name/value pair in my ajax call...it was a great idea, but I can't get it to work.

using this works fine to pass my form collection:

formCollection = $(':input');
        $.ajax({
            type: "POST",
            url: "/mycontroller/mymethod",
            data: formCollection,
            dataType: "text",
            success: showConfirm,
            error: function (xhr, textStatus, errorThrown) {
                alert(xhr.responseText);
            }
        });

but when I try and change my data to an object like this:

formCollection = $(':input');
        $.ajax({
            type: "POST",
            url: "/mycontroller/mymethod",
            data: ({collection: formCollection}),
            dataType: "text",
            success: showConfirm,
            error: function (xhr, textStatus, errorThrown) {
                alert(xhr.responseText);
            }
        });

it won't fly. I need to do that so ultimately I can use this:

formCollection = $(':input');
        $.ajax({
            type: "POST",
            url: "/mycontroller/mymethod",
            data: ({collection: formCollection, radiobutton: radiobuttonValue}),
            dataType: "text",
            success: showConfirm,
            error: function (xhr, textStatus, errorThrown) {
                alert(xhr.responseText);
            }
        });

my action method on the controller looks like this:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult mymethod(FormCollection collection)
        {
}

any ideas why when I change the data, it doesn't work?

Answer

Blazemonger picture Blazemonger · Sep 13, 2011

Try using formCollection = $('form').serialize() instead.

http://api.jquery.com/serialize

This will produce a string that looks like a GET query string, which you can use directly in your first code sample.