Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 244
TimTam Avatar asked Nov 05 '22 14:11

TimTam


1 Answers

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
 });
like image 175
Ryan Avatar answered Nov 11 '22 05:11

Ryan