将JSON传递给WEB API控制器

时间:2013-10-28 17:39:38

标签: asp.net-mvc asp.net-web-api

我有一个MVC WEB API控制器的模型。 匹配此模型结构的相应JSON是什么?

namespace CarEvaluator.Models
{
    [DataContract]
    public class Record
    {
        [DataMember]
        public List<Boolean> CHits { get; set; }

        [DataMember]
        public List<Boolean> MHits { get; set; }
    }
}




public void Post(Record record)
{

}

1 个答案:

答案 0 :(得分:1)

结构:

{"CHits":[true,false],"MHits":[true,false]}

示例:

var postObject = new Object();

// Initialize CHits and MHits as arrays
postObject.CHits = [];
postObject.MHits = [];

// push some items into the arrays
postObject.CHits.push(true);
postObject.CHits.push(false);
postObject.MHits.push(true);
postObject.MHits.push(false);

// serialize data to post
// this is what you set as data property in for instance jquery ajax
$.ajax({
    //other params, content type etc
    type: 'POST',
    data: JSON.stringify(postObject),
    ...
    });

如果参数为null,则应尝试添加[FromBody]属性并使用httppost

修饰方法
[HttpPost]
public void Post([FromBody]Record record)
{

}