views:

188

answers:

3

I would like to pass

{"id":1, "name":"stackoverflow", "parameter2":false, "parameter3":true}

To my action

public JsonResult Action(int id, string name, bool parameter2, bool parameter3)
{
    //...
}

Using JQueries ajax method using the JSON as the data parameter

$.ajax({
   url: "target.aspx",
   data:  {"id":1, "name":"stackoverflow", "parameter2":false, "parameter3":true},
   success: handleResponse
});

I can see in fiddler my JSON object is being sent up, but they are not being bound to my actions parameters. How do I get them to bind to the parameters?

I don't want to bind to an object on action which contains my values, ie I don't want Action(MyCustomObjectToAcceptParameters json) I want each JSON property to bind to each parameter of the action.

If I pass my parameters as a querystring everything works, but JSON is a lot easier to build/maintain than a bunch of querystring values so I would like something to take my json and bind it to each parameter on my action. I do not need to bind complex types with datamembers, just simple strings, ints and booleans.

A: 

womp gave you nice answer, but if you need to do this on several actions or you want more advanced binding to complex object, thise articles may help:

Implementing custom filter:http://blogger.forgottenskies.com/?p=252

Using custom model binder:http://community.codesmithtools.com/blogs/tdupont/archive/2009/08/10/mvc-custom-json-binder.aspx

Misha N.
+2  A: 

I see @womp removed his answer based on my feedback so here is the solution. You can pass a JSON object as the data parameter. See here for examples.

$.ajax({
   url: "target.aspx",
   data: {parameter1: true, parameter2: false, parameter3: true},
   success: handleResponse
 });
Ryan
If this is what you've done, can you use Firebug to confirm that the parameters are actually in the request? Or you could set a breakpoint in your controller and check the HttpContext.
Ryan
This is how I am passing my parameters, but how do I get them to bind to my actions parameters (not an object of the actions parameters);
TimTam
Are you using the default model binder? This should just work.
Ryan
Yes I am using the default model binder. When I pass my parameters as a part of the URL in querystring format it works. When I pass JSON through the data object it doesn't
TimTam
A: 

The binder/filter is excellent. For finer control on mapping json names <--> business class properties, use [DataMember] attribute on properties, and [DataContract] on the class. See DataContractJsonSerializer.

destroyer of evil
This looks like binding for properties on an object. I want to bind to the parameters of the action (so I don't need to create another object)
TimTam