在我的MVC4应用程序的ViewModel中,我有一些代码可以从ajax调用中获取名称,并在我的页面中填充一个简单的控件,该控件使用Bootstrap 3。正如您在下面看到的,我有一个硬编码的数组,它可以完美地工作。使用ajax调用,我可以看到UI中的数据,但它不会更新我的控件,我也不知道为什么。我已经验证了数据是否存在,并且还尝试在ajax调用中设置self.Names = ko.observableArray。有没有一个简单的原因?正如我所说的,我在两个场景中都看到了表单中的数据,但我没有看到我期望的更新。
$(document).ready(function () {
function ViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("");
var Names = {
Name: self.Name
};
self.Name = ko.observable();
//self.Names = ko.observableArray([{ Name: "Brian" }, { Name: "Jesse" }, { Name: "James" }]);
self.Names = ko.observableArray(); // Contains the list of Names
// Initialize the view-model
$.ajax({
url: '@Url.Action("GetNames", "Home")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Names(data); //Put the response in ObservableArray
}
});
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
});下面是通过ajax调用来自主体的响应:
[{"Id":1,"Name":"Brian"},{"Id":2,"Name":"Jesse"},{"Id":3,"Name":"James"}] 我的HTML
<p>Current selection is <span data-bind="text:Name"></span></p>
<div class="container">
<div class="col-sm-7 well">
<form class="form-inline" action="#" method="get">
<div class="input-group col-sm-8">
<input class="form-control" placeholder="Work Section" name="q" type="text">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Select <span class="caret"></span></button>
<ul class="dropdown-menu" data-bind="foreach: Names">
<li class="dropdown">
<a href="#" data-bind="text: Name, value: Name, click: function() {$root.Name(Name);}"></a>
</li>
</ul>
<input name="category" class="category" type="hidden">
</div>
</div>发布于 2014-03-08 01:10:49
可能是因为传入的数据的结构与您的绑定不同,或者没有正确设置/更新可观察对象。如果它们没有被观察到,那么它们就不会更新。
我不能百分之百地确定这一点,但我认为你必须使用可观察的数组函数,以便观察者(绑定到数组或其内容的UI元素)真正得到更新。这基于observable array documentation on the knockout site中的一节
2.对于修改数组内容的函数,比如push和splice,KO的方法会自动触发依赖项跟踪机制,以便将更改通知给所有注册的侦听器,并自动更新您的UI。
根据json的不同,一种可能的解决方法是清除可观察数组,并使用转换为可观察对象的数据元素重新加载它:
self.Names.removeAll();
var newName = null;
for (var idx = 0; idx < data.length; idx++) {
newName = data[idx];
newName.Id = ko.observable(newName.Id);
newName.Name = ko.observable(newName.Name);
self.Names.push(newName);
}在你的网页上。click函数使用所选数组元素的Name属性作为参数。你不想要这个,你想要最新的值。因此,请更改以下内容:
click: function() {$root.Name(Name);}到这个
//notice the new parenthesis after Name.
click: function() {$root.Name(Name());}https://stackoverflow.com/questions/22256165
复制相似问题