1

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

1
  • data: items: [{'name':'some'},{'name':'other'}] is incorrect JSON syntax. Try data: { 'items' : [{'name':'some'},{'name':'other'}]} instead. Commented Jul 8, 2013 at 4:57

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I think that the article you've linked to refers to an ASMX service operation, not an MVC4 HTTP service operation. I've used raw JSON data (i.e. not a string) against MVC4; it should work OK.
1

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.

Comments

1

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'}]
    }
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.