简体   繁体   中英

How do you pass a JSON object to an MVC action parameters?

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.

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
 });

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM