@brandy
To set a selected option in ASP.NET MVC using Knockout.js, you can follow these steps:
1 2 3 4 5 6 7 8 9 10 |
function ViewModel() { var self = this; self.options = ko.observableArray([ { id: 1, name: 'Option 1' }, { id: 2, name: 'Option 2' }, { id: 3, name: 'Option 3' } ]); self.selectedOption = ko.observable(); } |
1
|
<select data-bind="options: options, optionsText: 'name', optionsValue: 'id', value: selectedOption"></select> |
1 2 |
var viewModel = new ViewModel(); ko.applyBindings(viewModel); |
1
|
viewModel.selectedOption({ id: 2, name: 'Option 2' }); |
This way, the second option will be selected by default when the page loads. You can set the selectedOption
property dynamically based on your requirements.
That's it! By following these steps, you can set a selected option in ASP.NET MVC using Knockout.js.