3

我正在构建一个主要使用 ajax 调用的应用程序,但问题是我无法在 ajax 驱动页面中使用视图模型。

在我的用户列表中,我有一个包含用户列表的表,当单击编辑按钮时,Ajax 将编辑页面加载到#edit div。现在的问题是,在新页面加载到其中之后,我无法获取 vm 值。

ko.applyBindings(vm);

<div id="users">

</div>

<div id="edit">

</div> 

   this.EditAjax = function (user) {
            $.ajax({
                type: 'POST',
                data:'',
                url: '/Users/Edit/'+ user.id,

                success: function (h) {
                    $('#edit').html(h);
                }
            });
        };
4

2 回答 2

2

我发现当我们尝试将应用程序应用到 div 时没问题,但是每当我们将 ajax 驱动的页面加载到该 div 时,我们的绑定在该 div 内不再起作用。这解决了问题。所做的事情是在页面加载后使用 $.ajax 的 .then 将绑定应用到特定的 div。

function ajax() {
$.ajax({
    url: "/Home/Go",
    type: 'POST',
    success: function (h) {

        $('#sam').html(h);

    },
    error: function (m) {
        alert(m);
    }

})
.then(function () {

   ko.applyBindings(AppViewModel, document.getElementById("mm"));


});
于 2013-08-25T09:17:50.773 回答
0

检查这个小提琴 -

http://jsfiddle.net/p6WjJ/

您可以轻松地将编辑视图绑定到 Knockout observable。

<div id="users" data-bind="foreach: users">
    <span data-bind="text: name, click: editUser"></span>
</div>

<div id="edit" data-bind="with: editingUser">
    <input type="text" data-bind="value: name" />
</div>

在您的视图模型中

var editingUser = ko.observable();
var users = ko.observableArray();

function editUser(sender) {
    // If you already have all of your properties of User why not just set the editor to that instead of making another server call through AJAX?
    editingUser(sender);
}
于 2013-08-06T20:04:18.777 回答