ASP.NET web api和knockout js viewmodel数据没有从客户端绑定到服务器

时间:2014-10-01 13:37:38

标签: knockout.js asp.net-web-api

我在将数据从jquery ajax帖子发布到asp.net web api方法时遇到问题。日期属性显示在Web控制台中,由两个双引号括起,然后重置,布尔属性设置为null。

使用Javascript:

self.startTime = ko.observable(startTime); 
    self.startTimeDate = ko.computed({
        read: function() {
            return moment(self.startTime()).format("MM-DD-YYYY HH:MM:ss");
        },
        write: function(value){
            self.startTime(moment(value).format("MM-DD-YYYY HH:MM:ss"));
        }
    });

    self.endTime = ko.observable(endTime); 
    self.endTimeDate = ko.computed({
        read: function () {
            return moment(self.endTime()).format("MM-DD-YYYY HH:MM:ss");
        },
        write: function (value) {
            self.endTime(moment(value).format("MM-DD-YYYY HH:MM:ss"));
        }
    });



self.includeDeviceAddedToInventory = ko.observable(true); 
var model = {
            auditLogType: ko.toJSON(self.auditLogType),
            id: ko.toJSON(self.auditLogId),
                entriesPerPage: ko.toJSON(self.entriesPerPage), 
                    pageNumber: ko.toJSON(self.pageNumber), 
                startTime: ko.toJSON(self.startTimeDate), 
                    endTime: ko.toJSON(self.endTimeDate), 
                    includeDeviceAddedToInventory: ko.toJSON(self.includeDeviceAddedToInventory) 

...

$.post("api/AuditLog", { filterInfo: model })

javascript控制台将对象显示为:

entriesPerPage:" 0", pageNumber:" 0", 结束时间:"" 10-01-2014 06:10:00"", startTime:"" 10-01-2014 06:10:00"", includeDeviceAddedToInventory:" true"

然而.net调试器将对象显示为: entriesPerPage:0, pageNumber:0, 结束时间:{1/1/0001 12:00:00 AM}, startTime:{1/1/0001 12:00:00 AM}, 空

ASP.NET

public class PostModel
    {
public int EntriesPerPage { get; set; }
        public int PageNumber { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public string IncludeDeviceAddedToInventory { get; set; }
}

    public HttpResponseMessage Post(PostModel filterInfo)
            {

我尝试使用无法工作的newtonsoft web api属性进行序列化。但语法可能不正确。有人可以发贴样品或帮忙吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

ko.toJSON(以及应用于字符串的基础JSON.stringify)会将其用双引号括起来(它们将成为结果的一部分):

ko.toJSON("aaa") = "\"aaa\""

当一个对象的成员是ko.toJSON的结果并且该对象也被序列化为JSON(当发送到服务器时)时,您还将获得这些额外的引号。解决方案很简单,不要单独序列化属性,使用实际值创建对象并发送它,它将作为一个整体序列化:

var model = {
    auditLogType: self.auditLogType,
    id: self.auditLogId,
    entriesPerPage: self.entriesPerPage, 
    pageNumber: self.pageNumber, 
    startTime: self.startTimeDate, 
    endTime: self.endTimeDate, 
    includeDeviceAddedToInventory: self.includeDeviceAddedToInventory 

...

$.post("api/AuditLog", { filterInfo: model })