简体   繁体   English

如何通过可观察属性(剔除)进行查看

[英]How to pass a observable property (of knockout) to view

I am having a dropdown binded with a ko.observableArray([]). 我有一个与ko.observableArray([])绑定的下拉列表。 Here I am capturing selected value in vm.selectedUser which is a ko.observable(). 在这里,我正在vm.selectedUser中捕获选择的值,这是一个ko.observable()。 I want to assign this value to a hidden field in view on onchange event @Html.HiddenFor(m => m.UserName, new {id="hiddenUser" }) 我想将此值分配给onchange事件@ Html.HiddenFor(m => m.UserName,新{id =“ hiddenUser”})上的隐藏字段

$("#hiddenUser").val(vm.selectedUser); $(“#hiddenUser”)。val(vm.selectedUser);

Please help. 请帮忙。 Thanks 谢谢

you can subscribe to change to do that 您可以订阅更改以执行此操作

vm.selectedUser.subscribe(function(newValue) {
    $("#hiddenUser").val(newValue));
});

or just bind the hidden field to your observable, that should work too 或只是将隐藏字段绑定到您的可观察范围,这也应该起作用

@Html.HiddenFor(m => m.UserName, new {id="hiddenUser",data_bind = "value: selectedUser" })

You can do something like this DEMO (I have created my fiddle in my own coding style, may or may not match yours, Apologies! ) 您可以执行类似DEMO的操作 (我以自己的编码风格创建了小提琴,抱歉,可能与您不匹配,抱歉!)

Assuming, 假设,

var Users = ko.observableArray([]);//Your User List
var SelectedUser=ko.observable();//Your Dropdown selected Item, can be ID or Name.

You can write/define a function for change event of dropdown:- 您可以为下拉菜单的更改事件编写/定义函数:-

function selectionChanged(data){
console.log(SelectedUser());
    $('#hiddenUser').val(SelectedUser());//Displaying it in Textbox
            $('#hiddenUser2').val(SelectedUser());//Saving it in hidden field

};

Where my HTML markup would be as follows:- 我的HTML标记如下:

<select data-bind="options: Users, optionsText: 'Name', optionsValue: 'Id',value: SelectedUser,event: { change: selectionChanged }"></select>

<input type="text" id="hiddenUser"></input>
<input type="hidden" id="hiddenUser2"></input>

You can also look into Fiddle Example by RP Niemeyer 您还可以查看RP Niemeyer的Fiddle示例

No need for jQuery and a subscribe, just bind the hidden input directly to the selectedUser observable: 无需jQuery和订阅,只需将隐藏的输入直接绑定到selectedUser可观察的对象即可:

@Html.HiddenFor(m => m.UserName, new {id="hiddenUser", data_bind="value: selectedUser" })

Note that it is "data_bind" instead of "data-bind". 请注意,它是“ data_bind”而不是“ data-bind”。 In Razor, the dash is an invalid name character, but it will automatically convert the underscore to a dash. 在Razor中,破折号是无效的名称字符,但是它将自动将下划线转换为破折号。

[Don't mean for this to be an advertisement, but this is one of the items I demonstrate in my video on using Knockout and MVC together at WintellectNOW dot com if you are interested.] [这并不意味着要成为广告,但这是我在视频中演示的关于在WintellectNOW dot com上同时使用Knockout和MVC的项目之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM