在MVC局部视图不能applybindings多次淘汰赛 [英] cannot applybindings multiple times knockout in MVC partial view

查看:303
本文介绍了在MVC局部视图不能applybindings多次淘汰赛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜有,我已经使用淘汰赛JS绑定模型HTML元素的父页面。

Hi have a parent page in which i have used knockout js to bind model with html element.

现在我做一个AJAX调用接收partialviewresult,我把它放在一个div conbtainer。

Now i make a ajax call to receive a partialviewresult which i place it in a div conbtainer.

所有工作正常,如果使用内置的MVC模式的结合。

All works fine if use the inbuilt mvc model binding.

但是,当我去为淘汰赛在我的局部视图以及。我得到的errorcannot applybindings多次在MVC局部视图淘汰赛。

But when i go for knockout in my partial view as well. I get the errorcannot applybindings multiple times knockout in MVC partial view.

我甚至已经尝试使用

ko.applybindings(new vm(),document.getelementbyId("div1"))
ko.applybindings(new vm1(),document.getelementbyId("div2"))

但仍然得到同样的错误。这难道不是可以从操作方法得到局部视图的结果,在局部视图中使用的淘汰赛?我不想隐瞒我的父页面div和获得JsonResult并将其绑定到我的div元素。

But still get the same error. Is it not possible to get the partial view result from the action method and use knockout in partial view ? I do not want hide the div in my parent page and get a JsonResult and bind it to my div element.

推荐答案

如果您有以下(常规布局):

If you have the following (general layout):

<div id="parent">
  content
  <div id="partialTarget"></div>
</div>

和你已经应用于您绑定#parent,你必须重新申请视图模型前清洁#partialTarget。 #partialTarget已经从第一阶段的约束,所以要绑定应用于加载内容,你需要做的是这样的:

and you've already applied your bindings to #parent, you have to clean #partialTarget before applying the viewmodel again. #partialTarget has already been bound from the first pass, so to apply the bindings to the loaded contents, you need to do something like this:

var reapplyBindings = function(element){
    var vm = ko.dataFor(element);
    if( vm ) {
        ko.cleanNode(element);
        ko.applyBindings(vm, element);
    }
};

element.load(‘path/to/fragment.html’, function() {
    //the [0] selector is needed to be sure we have an actual dom element, not the jQuery wrapper
    reapplyBindings(element[0]); 
    //do whatever you’re already doing
});

这篇关于在MVC局部视图不能applybindings多次淘汰赛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆