Knockout JS href attr 未绑定在 .NET MVC4 部分页面上

Knockout JS href attr not binding on .NET MVC4 partial page

本文关键字:MVC4 分页 NET href JS attr 绑定 Knockout      更新时间:2023-09-26

我是一个中等的淘汰赛用户,但这是我第一次在MVC4环境中使用它。所有常用的绑定都正常工作,但是我遇到了一个问题,即当我加载然后绑定部分视图时,我的href属性绑定似乎没有触发。

这是我的部分视图标记:

<div id="quick-panel">
    <a class="icon-set" data-bind="attr: { href: Contact.fullEditUrl() }" >&#x1F4DD;</a>
</div>
<div id="rightbarcontent">
....
</div>
<script>
ko.applyBindings(window.contact.viewmodel, document.getElementById("rightbarcontent"));
</script>

这是我的视图模型片段,我在其中定义了 Contact.fullEditUrl():

window.contact.Contact = function (data) {
    var contact = this;
    this.id = ko.observable(data.id);
    this.fullEditUrl = ko.computed(function() {
        return "http://localhost:24191/contact/contactfulledit/" + data.id;
    });
}

我在加载 DOM 后触发命名空间绑定。我在同一页面上的所有其他绑定(大约 20 个)都是正确的,但是 href 从未为我的锚标签设置过,我不确定为什么。我已经在各种站点和线程上仔细检查了我的语法,它似乎是正确的

你想要 this.id()而不是 data.id()

Id 还建议你制作它

window.contact.Contact = function (data) {
   var contact = this;
   contact.id = ko.observable(data.id);
   contact.fullEditUrl = ko.computed(function() {
       return "http://localhost:24191/contact/contactfulledit/" + contact .id();
   });
}

如果 id 永远不会改变(看起来不像,你根本不需要使用任何可观察或计算的:

window.contact.Contact = function (data) {
   var contact = this;
   contact.id = data.id;
   contact.fullEditUrl = "http://localhost:24191/contact/contactfulledit/" + contact.id
}

您只需要在需要跟踪的某些内容发生变化时使用可观察性。

就部分而言。部分是否包含在主上下文中(您在 ko.applyBindings 中绑定的内容)?因为如果不是,那么ko将无法找到它。

我建议你把所有东西都包装在另一个div中并绑定到它。

但是,如果您已经在主页上绑定了一些内容,则其中包含其中。然后再次应用绑定将失败。在这种情况下,我建议您做以下两件事之一:

1) 将它们组合到相同的绑定上下文中。2) 确保主页中的绑定和部分绑定不重叠。重叠的绑定将导致它们失败。