2

public class PostModel {

        public string Value { get; set; }

        public IList<TestModel> TestValues { get; set; }

}

public class TestModel {      

        public string Value { get; set; }

}

jQuery script:

 var testValue1 = {

        Value: "val2"

 };

 var testValue2 = {

        Value: "val3"

 };

var model = {

            Value: "test",

            TestValues: [testValue1 , testValue2]

        };

  jQuery.post(url, model, function (data) {
                alert(data);
            }
        );

public ActionResult Test(PostModel model)

{

     model.Value // is OK, = "test"

     model.TestValues// is OK, count = 2

     model.TestValues[0].Value // why is null ???? 

     return Content("Ok");

}

How Bind nested objects ?

1 Answer 1

3

The json data posted to the MVC controller must be a collection of key-value pairs representing the names and the values of the posted form. In order to bind to a complex model you need to send something like this.

var jsonData = {};
jsonData['TestValues[0].Value'] = '...';
jsonData['TestValues[1].Value'] = '...'; // binds to model.TestValues[1].Value
jsonData['Value'] = '...'; // binds to model.Value
$.post(url, jsonData, ...);
Sign up to request clarification or add additional context in comments.

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.