4

possible duplicate Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

but my question is when I pass

var things = [
  {employee:'test',effectiveDate:'',expirationDate:'' },
  { employee:'test',effectiveDate:'',expirationDate:'' }
];

$.ajax({
 contentType: 'application/json',
 type: "POST",
 url: "/MyController/CheckMethod",
 dataType: "json",
 data: JSON.stringify(things),
 async: false,
 success: function (data) {

to an controller method which is a [HTTPPOPST] JsonResult then I'm getting value into my List<MYMODEL>

but when I take a controller method as 'ActionResult' then i'm getting null in List<MYMODEL>

why so any thing wrong?

Community
  • 1
  • 1
Neo
  • 15,491
  • 59
  • 215
  • 405
  • Works fine for me in controller methods of both types `JsonResult` and `ActionResult`. Show me both the controller methods? – kelsier Nov 28 '14 at 04:52

3 Answers3

4

I think first of all your JSON should be strongly typed. and once it already strongly typed you need not use JSON.stringfy. instead go with,

data: {"things" : things},

and your controller should be like

public IActionResult ActionName(List<Model> things)
Sarvagya Saxena
  • 229
  • 1
  • 9
  • Wrong! You cannot bind a an array of objects to a `List` unless its `stringified` (and `IActionResult` is core-mvc, not mvc) –  Feb 26 '18 at 20:47
3

You have an error in the ajax function. Assuming your controller method is

public ActionResult CheckMethod(List<MYMODEL> items)

Then it should be

data: JSON.stringify('items': things),

not

data: JSON.stringify(things),
2

It should work with both scenarios as JsonResult is just a type of ActionResult (see here for more information).

If your action only returns JSON data, stick with JsonResult; it makes your action less error-prone as Visual Studio will let you know if you accidentally try to return another type of result. Use ActionResult when your action returns more than one type of result.

That being said, Stephen Muecke's observation is correct; assuming your action is expecting a List<MYMODEL>, you're "stringifying" your objects but are not assigning them to a variable. Make sure that the variable name you declare in the AJAX function has the same name as the parameter your ActionResult (or JsonResult) expects.

trashr0x
  • 6,457
  • 2
  • 29
  • 39