How to set selected option in asp.net mvc using knockout.js?

Member

by brandy , in category: Javascript , 2 days ago

How to set selected option in asp.net mvc using knockout.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , a day ago

@brandy 

To set a selected option in ASP.NET MVC using Knockout.js, you can follow these steps:

  1. Create a ViewModel in your JavaScript file with the options you want to select from:
 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. In your ASP.NET MVC View, bind the ViewModel to your HTML elements using Knockout.js syntax:
1
<select data-bind="options: options, optionsText: 'name', optionsValue: 'id', value: selectedOption"></select>


  1. Initialize the ViewModel and apply bindings to your View:
1
2
var viewModel = new ViewModel();
ko.applyBindings(viewModel);


  1. To set a default selected option, you can set the selectedOption property of your ViewModel to the desired option:
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.