Patrick Lee Scott
Patrick Lee Scott

Reputation: 8699

ASP.net MVC and jQuery serialize multiple forms to list of objects and submit

Using asp.net mvc3 and jquery

I have x number of forms on a page, each created when a user adds a new item. Each form represents a model in c#. Each form has a list of strings as one of the properties. I want to have a save all button that submits all of the forms, but I would like to serialize them into one list of objects before I do so, and then sort it out in the back end. How can I do this with jQuery?

<form>
    <input name="ListThing" value="one" />
    <input name="ListThing" value="two" />
    <input name="ListThing" value="three" />
    <input name="Name" value="Bob" />
</form>

<form>
    <input name="ListThing" value="one" />
    <input name="ListThing" value="two" />
    <input name="ListThing" value="three" />
    <input name="Name" value="Pat" />
</form>

c#

public class myModel{
    public List<string> ListThing {get; set;}
    public string Name {get; set;}
}

controller - UploadController -action

[HttpPost]
public ActionResult SaveAll( List<myModel> myModels )
{
    // do stuff
    return View();
}

Upvotes: 3

Views: 6529

Answers (2)

Fabian Nicollier
Fabian Nicollier

Reputation: 2861

Darin's solution works but personally I would use http://www.malsup.com/jquery/form/ to Ajaxify the forms without having to do the mapping by hand. ASP.Net MVC's Default Binder will bind multiple elements with the same name (or the same name with a sequential "[X]" indexer) as a List.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You cannot have multiple elements with the same id. So start by fixing your markup:

<form>
    <input name="ListThing" value="one" />
    <input name="ListThing" value="two" />
    <input name="ListThing" value="three" />
    <input name="Name" value="Bob" />
</form>

<form>
    <input name="ListThing" value="one" />
    <input name="ListThing" value="two" />
    <input name="ListThing" value="three" />
    <input name="Name" value="Pat" />
</form>

and then assuming you have some link to trigger the action:

@Html.ActionLink("Save all", "SaveAll", "Home", null, new { id = "saveall" })

you could simply AJAXify it:

$('#saveall').click(function () {
    var data = $('form').map(function () {
        var $form = $(this);
        return {
            name: $form.find(':input[name=Name]').val(),
            listThing: $form.find(':input[name=ListThing]').map(function () {
                return $(this).val();
            }).toArray()
        };
    }).toArray();

    $.ajax({
        url: this.href,
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify({ myModels: data }),
        success: function (result) {
            alert('done');
        }
    });

    return false;
});

Upvotes: 7

Related Questions