ASP.Net WebAPI Post Method显示空值

时间:2014-05-14 09:01:11

标签: c# javascript asp.net-mvc-4 knockout.js asp.net-web-api

我从昨天开始就被困在这个问题上。我开始用ASP.Net WebAPI学习knockoutjs。一切都运行良好,直到我将数据发回API控制器。每当我将数据压缩到控制器时,它都会为Person对象的每个字段显示空值。

enter image description here

我试过一切,例如使用带有contentType的$ .ajax:'application / json',或contentType:'application / json,utf-8 ...',但对我来说没有任何作用。请给出一些解决方案,我将非常感谢你..

这是WebAPI Post Method的代码:

// POST api/some
public HttpResponseMessage Post([FromBody]Person value)
{
    repository.SavePerson(value);
    return Request.CreateResponse(HttpStatusCode.OK);
}

这是Person class

public class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public List<string> activities { get; set; }
    public string favoriteHobby { get; set; }
}

这是javascript / knockout code

function PersonViewModel() {
    var self = this;

    self.firstName = ko.observable('');
    self.lastName = ko.observable('');
    self.activities = ko.observableArray([]);
    self.favoriteHobby = ko.observable('');

    self.loadUserData = function () {
        $.getJSON("api/Some/Get", function (data) {
            self.firstName(data.firstName);
            self.lastName(data.lastName);
            self.activities(data.activities);
            self.favoriteHobby(data.favoriteHobby);
        });
    }

    self.saveUserData = function () {
        var data_to_send = { value: ko.toJSON(self) };
        $.post("api/Some/Post", data_to_send, function (data) {
        });
    }
};

ko.applyBindings(new PersonViewModel());

最后这里是HTML

<form action="#" method="post">
<p>
    First name:
    <input data-bind='value: firstName' />
</p>
<p>
    Last name:
    <input data-bind='value: lastName' />
</p>
<div>
    Your favorite food:
    <select data-bind='options: activities, value: favoriteHobby'>
    </select>
</div>
<p>
    <button data-bind='click: loadUserData'>Load Data</button>
    <button data-bind='click: saveUserData'>Save Data</button>
</p>
</form>

2 个答案:

答案 0 :(得分:2)

如果你想发布像

这样的JSON
{ "value" : {"firstName" : "Jane", "lastName" : "Doe" }  }

到ApiController方法,你需要添加一个额外的“模型”服务器端

public class ValueModel
{
    public Person value { get; set; }
} 

public class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public List<string> activities { get; set; }
    public string favoriteHobby { get; set; }
}

public HttpResponseMessage Post([FromBody]ValueModel model) { .. }

或者,将{"value": ..}放入JSON中,然后发布var data_to_send = ko.toJSON(self)

这是因为模型绑定器绑定了您发布的JSON的完全相同的“结构”。

答案 1 :(得分:0)

您发送的数据不是JSON;只有属性value。为了使JSON发布工作,您应该将整个对象序列化为JSON并设置内容类型:

var data_to_send = ko.toJSON({ value: self });
$.ajax({
    url: "api/Some/Post",
    type: 'POST',
    data: data_to_send ,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: false,
    success: function(data) {

    }
});

但是你也应该能够发布表单数据而不是JSON:

var data_to_send = { value: ko.toJS(self) };
$.post("api/Some/Post", data_to_send, function (data) {
});