简体   繁体   中英

How to pass a observable property (of knockout) to view

I am having a dropdown binded with a ko.observableArray([]). Here I am capturing selected value in vm.selectedUser which is a 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" })

$("#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! )

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:-

<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

No need for jQuery and a subscribe, just bind the hidden input directly to the selectedUser observable:

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

Note that it is "data_bind" instead of "data-bind". In Razor, the dash is an invalid name character, but it will automatically convert the underscore to a dash.

[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.]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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