来自KnockoutJs ViewModel的Web Api帖子

时间:2012-12-14 21:44:26

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

我在web api帖子上找不到太多信息。这是一篇博客文章,我发现有关如何从淘汰赛中进行POST的讨论。 Web Api POST with KnockoutJs ViewModel

ViewModel:

<script type="text/javascript">

var QuickEntry = function (_itemPartNumb, _itemDescription, _itemQuanities) {
    this.ItemPartNumb = ko.observable(_itemPartNumb);
    this.ItemDescription = ko.observable(_itemDescription);
    this.ItemQuanties = ko.observable(_itemQuanities);
};

function QuickEntriesViewModel() {

    var self = this;
    self.quickEntries = ko.observableArray([]);

    for (var i = 0; i < 10; i++) {
        self.quickEntries.push(new QuickEntry());            
    }

    self.addNewRow = function () {
        self.quickEntries.push(new QuickEntry());            
    }.bind(self);

    self.addToCart = function() {
        var items = ko.toJSON(self);

        $.ajax({
            url: '/DesktopModules/blah/API/Data/Post',
            type: 'POST',
            data: items,
            datatype: "json",
            processData: false,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert(data);
            },
            statusCode: {
                404: function () {
                    alert('Failed');
                }
            }
        });
    };
};

ko.applyBindings(new QuickEntriesViewModel());

DataController(Web Api)

[HttpPost]
public string Post(quickEntries values)
{
    string response = string.Empty;
    response = values.Items != null ? "some data" : "nothing at all";

    return response;
}

//class
public class quickEntries
{
    public MyQuickEntry[] Items { get; set; }
}

public class MyQuickEntry
{
    public string ItemPartNumb { get; set; }
    public string ItemDescription { get; set; }
    public string ItemQuanties { get; set; }
}

这是从fiddler传递给web api POST方法的原因:

  

{ “quickEntries”:[{ “ItemPartNumb”: “鲍勃”, “ItemDescription”: “鲍勃”, “ItemQuanties”: “鲍勃”},{},{},{},{},{}, {},{},{},{}]}

有没有人有将json对象数组传递给web api的经验?

3 个答案:

答案 0 :(得分:2)

问题是您发送的是ViewModel,而不是对象数组:

var items = ko.toJSON(self);

这会将整个ViewModel对象转换为JSON。尝试只转换数组:

var items = ko.toJSON(self.quickEntries);

答案 1 :(得分:0)

事实证明我需要重命名我的课程。

public class RootObject
{
    public List<QuickEntry> quickEntries { get; set; }
}

public class QuickEntry
{
    public string ItemPartNumb { get; set; }
    public string ItemDescription { get; set; }
    public string ItemQuanties { get; set; }
}

答案 2 :(得分:0)

以下不是一个直接的答案 - 但是一些有用的链接将Knockout与Web API一起使用(虽然我还没有尝试使用淘汰赛进行开发,但文章内容丰富)

  1. Single-Page Applications: Build Modern, Responsive Web Apps with ASP.NET
  2. KNOCKOUTJS AND WEBAPI TRICKS ARE FOR POCO, KIDS.
  3. Single Page Application: KnockoutJS template
  4. Using AngularJS to send parameters to Web API