Reputation: 36224
Apparently I am doing something wrong, Tried everything.
Initially I needed to send array of objects to asp.net mvc controller using angular's $http, well it didn't work.
Then I tried to use jquery. I've tried $.get
, $.post
, $.ajax
methods with different parameters (traditional, non-traditional, with dataType:'json'
, without it - still can't pass the values. This thing is killing me.
$.ajax(
url: '/Home/Foo'
data: items: [{'name':'some'},{'name':'other'}])
public JsonResult Foo(Item[] items)
{
return Json(items, JsonRequestBehavior.AllowGet);
}
public class Item
{
public string name { get; set; }
}
The best what I could get out of it - it recognizes items as Item[] array but every name
value is null
Upvotes: 1
Views: 2398
Reputation: 14737
Your data
string (i.e. data: items: [{'name':'some'},{'name':'other'}]
) is invalid JSON syntax, while your stringified JSON string in your self-answer is of correct syntax.
You shouldn't have to convert your object into a JSON string, and a standard Javascript object should work.
Try switching that to:
$.ajax(
url: '/Home/Foo',
data: {
'items': [{'name':'some'},{'name':'other'}]
}
)
Upvotes: 1
Reputation: 60580
When passing a JSON string to MVC, be sure to set a Content-Type of application/json
. Otherwise, MVC will expect the data in URLEncoded format instead of JSON.
JSON typically does work best for passing in arrays though, so you should be on the right path.
Upvotes: 1
Reputation: 36224
according to this article
http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/
it should be a string:
$.ajax(
url: '/Home/Foo'
data: "{ 'items': [{'name':'some'},{'name':'other'}] }"
Now using JSON.stringify should solve my problem. Still gotta try using $http
Upvotes: 1