我有一个输入字段:
<input id="DeviceId"
class="form-control deviceCatalog"
data-bind="value:DeviceTemp, valueUpdate: ['blur']"
required />
哪个绑定到此viewModel;
var ViewModel = function () {
var self = this;
self.DeviceTemp = ko.observable();
}
我在其上使用jQueryUI自动完成功能:
function GetNames() {
var availableTags;
var jsonData
$.ajax({
url: "/DeviceInstance/GetDeviceNames",
type: "GET",
dataType: "json",
error: function (data) {
alert("wystąpił nieokreślony błąd " + data);
},
success: function (data) {
availableTags = data;
availableTags = jQuery.map(data, function (n) {
return (n.name);
});
console.log(availableTags);
$(".deviceCatalog").autocomplete({
source: availableTags
});
}
})
};
获取数据:
public string GetDeviceNames()
{
var data = unitOfWork.deviceRepository
.Get()
.Select(w =>new {
name= w.CatalogNo + " " + w.Name,
Id=w.Id
})
.ToArray();
return JsonConvert.SerializeObject(data);
}
正如你所看到的,它正在获得Name + Id。
如何将所有这些绑定在一起以满足此要求:
name
自动填充,但Knockout会将Id存储在可观察的答案 0 :(得分:1)
这就是我需要做的事情:
第一: 从该输入解除绑定:
<input id="DeviceId" class="form-control deviceCatalog" required />
修改Ajax调用: 从:
$(".deviceCatalog").autocomplete({
source: availableTags
});
为:
$(".deviceCatalog").autocomplete({
source: availableTags,
change: function (event, ui)
{
viewModel.DeviceTemp(ui.item.id);
}
});
正如您所看到的,我添加了change
事件,我在其中修改了observable。因此,它存储元素的ID。
最后但并非最不重要的是我需要更改我的控制器方法: 从:
var data = unitOfWork.deviceRepository.Get().Select(w =>new {name= w.CatalogNo + " " +w.Name, Id=w.Id }).ToArray();
为:
var data = unitOfWork.deviceRepository.Get().Select(w =>new {label= w.CatalogNo + " " +w.Name, id=w.Id }).ToArray();
我将name
更改为label
。现在JQuery正确地看到我的标签应该在自动完成中使用。