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?

1
  • Works fine for me in controller methods of both types JsonResult and ActionResult. Show me both the controller methods?
    – kelsier
    Commented Nov 28, 2014 at 4:52

3 Answers 3

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)
1
  • Wrong! You cannot bind a an array of objects to a List<T> unless its stringified (and IActionResult is core-mvc, not mvc)
    – user3559349
    Commented Feb 26, 2018 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),
0
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.