【问题标题】:ASP.NET using Knockout.js and mappings使用 Knockout.js 和映射的 ASP.NET
【发布时间】:2012-09-21 08:51:50
【问题描述】:

使用以下代码我遇到了一个奇怪的问题。当我单击并调用 showVacationModal 时,可以从服务器很好地检索数据并正确显示结果。如果我继续点击同一个人(id),它会继续工作。

如果我点击没有假期的其他人(例如不同的 ID),则不会显示任何内容 = OK。

问题

现在,当我再次单击第一个人时,什么都没有显示。 (在 ajax 调用中可以正常检索数据)。

有什么想法吗?

我的JS代码:

var ViewModel = function () {
        this.vacations = ko.mapping.fromJS(null);
    };

    var model = new ViewModel();


    function showVacationModal(id) {
        var model = {};
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetVacations",
            data: "{personId: '" + id + "'}",
            delay: 1,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                model.vacations = ko.mapping.fromJS(msg.d);
                ko.applyBindings(model);


                $('#vacationModal').modal('show')
            }
        });

    }

我的 HTML:

<table>
                <thead>
                    <tr>
                        <th>
                            First name
                        </th>
                        <th>
                            Last name
                        </th>
                    </tr>
                </thead>
                <tbody data-bind="foreach: vacations">
                    <tr>
                        <td data-bind="text: Id">
                        </td>
                        <td data-bind="text: PersonId">
                        </td>
                        <td data-bind="text: Begin">
                        </td>
                    </tr>
                </tbody>
            </table>

【问题讨论】:

标签: javascript jquery asp.net knockout.js knockout-mapping-plugin


【解决方案1】:

您是否尝试过类似的方法?

function showVacationModal(id) {
    // var model = {}; no need to reset the model property
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetVacations",
        data: { personId: id }, // why wrap data in strings?
        delay: 1,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {

            //model.vacations = ko.mapping.fromJS(msg.d);
            ko.mapping.fromJS(msg.d, {}, model.vacations);
            // ko.applyBindings(model); no need to reapply bindings

            $('#vacationModal').modal('show')
        }
    });
}

更多信息请参见this ko.mapping documentation section

【讨论】:

  • 您在代码中遇到了问题:我认为真正的问题是重新发布绑定。
  • @JoelCochran 是的,ko.mapping.fromJS 在我尝试时总是返回一些时髦的东西。传入第二个和第三个参数对我来说总是有用的。
猜你喜欢
  • 2016-06-26
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 2013-01-07
相关资源
最近更新 更多