views:

82

answers:

1

I have an ASP.NET MVC action method which uses model binding to accept a strongly typed model object as its input, i.e:

public PartialViewResult SaveUser([Bind(Prefix = "User")]User NewUser)
{
}

How do I specify the argument when requesting this method asynchronously with JQuery? I have previously used the load() or post() methods to make asynchronous requests, but this was with only one or two named parameters. How do I pass the entire form data with async requests to this method?

This is one approach I have tried:

$.post('/Users/SaveUser/', { NewUser: $('#theForm') }, function(responseText, status) {
    $('#mainContent').text(responseText);
}, 'html');

I added a breakpoint in the action method and the NewUser parameter is null.

Am I completely off with this approach? Any help is much appreciated.

Thanks.

+1  A: 

You need to create a mapping between the input names and their values. The model binder will be expecting to see:

User.Name=username
User.FirstName=Bill
User.LastName=Gates
...

as the form parameters on the request. Try using the serialize method.

$('form').serialize()

to construct your parameters for the AJAX call.

tvanfosson
This worked a treat, thank you! I never knew about the serialize method.
Lee D