Posting complex object to MVC3 controller using jquery

Not as easy as it should be. I fought with this for way too long.
Basically, you should be able to construct the object in the $.post function call. But, for whatever reason, you cannot. Well, I couldn’t – your luck might be different.

this fails:

$.post("/SomeController/ActionThatAcceptsPost", {
Property1: someValue,
Property2: 3.0
}, function(response) {
//Make happy noises

but this works:

var thisIsTheParameterName = {
Property1: someValue,
Property2: 3.0
$.post("/SomeController/ActionThatAcceptsPost", thisIsTheParameterName
function(response) {
//moar happy noises

So, in short – make a variable to pass in a complex object to your MVC3 controller and it starts working.

Oh, and not sure if it matters, but the variable was the same name as the parameter on the Action, and the class was all [DataContract] decorated. Those two may be overkill, but I didn’t feel like taking them out to check.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: