1

I want to post an object that has list of another object inside, MVC is receiving the object as null.

MVC Post

[HttpPost]
public ActionResult Create(ObjectWithList objectWithList) { 
  // While debugging objectWithList has its properties null
}

ObjectWithList

public class ObjectWithList
{
    public List<Foo> Foo { get; set; }
    public AnotherFoo AnotherFoo { get; set; }
}

Foo and AntoherFoo are classes with normal properties, like string, etc.

Using Postman I POST: Headers: Content-Type as application/json Body (raw):

{
    "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "[email protected]"
   }
}

If I just pass "Foo" empty:

{
    "Foo": [
            {}
    ]
    ...

it works, (fills AnotherFoo). But as soon as i try to pass something inside Foo, MVC gets everything as null.

I'm correctly naming the properties of Foo and AnotherFoo on the JSON

2

2 Answers 2

1

Have you tried the [FromBody] attribute on the controller action?

[HttpPost]
public ActionResult Create([FromBody]ObjectWithList objectWithList) { 

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

Comments

0

Try something like:

var foos = {
 "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "[email protected]"
   }
};

$.ajax({
    url: "YourUrl",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({ objectWithList: foos })
}).done(function(result){
//do something
});

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.