开发者

asp mvc2, How Post and Bind nested objects?

开发者 https://www.devze.com 2023-03-07 23:07 出处:网络
public class PostModel { public string Value { get; set; } public IList<TestModel> TestValues { get; set; }

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) {
   开发者_如何学Python             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 ?


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, ...);
0

精彩评论

暂无评论...
验证码 换一张
取 消