Passing A List Of Objects Into An ActionResult MVC Controller Method Using jQuery Ajax
Solution 1
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)
Solution 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.
Neo
Hi! I'm a software engineer. Having experience to work on C#,Asp.Net,AJAX,SQL 2005/08/2012,EF4,SQL to LINQ and also worked on Cloud Computing (Microsoft Windows Azure and AWS Amazon).
Updated on June 28, 2022Comments
-
Neo almost 2 years
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 gettingvalue
into myList<MYMODEL>
but when I take a controller method as
'ActionResult'
then i'm gettingnull
inList<MYMODEL>
why so any thing wrong?
-
Admin about 6 yearsWrong! You cannot bind a an array of objects to a
List<T>
unless itsstringified
(andIActionResult
is core-mvc, not mvc)