This WIKI displays how to populate a dropdown using KNockOutJS with jQuery.
KNockOutJs is a JavaScript Library which used MVVM pattern and provides multiple functionality like Client Side and Server side code integration, Dynamic Data Binding, Dynamic UI etc. You can find more information about KnockOut from http://knockoutjs.com/ .
So, At First add reference of jQuery and KnockOut Library to page
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="knockout.js"></script>
Put following markup
<p>
Your country:
<asp:DropDownList ID="ddlCountries" runat="server" data-bind="options: countryModel.countries, optionsValue: 'CountryID', optionsText: 'CountryName', optionsCaption: 'Choose...'">
</asp:DropDownList>
</p>
<input type="button" value="Add" data-bind="click: addCountry" />
Add script tag to page as follows:
<script type="text/javascript">
function DropDownModel() {
var self = this;
self.countries = ko.observableArray();
self.addCountry = function () {
$.ajax({
type: "POST",
url: "DropDownSolution.aspx/GetCountries",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.countries(data.d);
}
});
};
}
var countryModel = new DropDownModel()
ko.applyBindings(countryModel);
</script>
In this script DropDownSolution.aspx is aspx page which contains a page method with the name GetCountries.
Add following code as your page method:
[WebMethod]
public static List<Country> GetCountries()
{
List<Country> countries = new List<Country>();
countries.Add(new Country { CountryID = "1", CountryName = "India" });
countries.Add(new Country { CountryID = "2", CountryName = "Singapore" });
countries.Add(new Country { CountryID = "3", CountryName = "Malaysia" });
return countries;
}
you can implement any logic in GetCountries() Method and return all records in a List.
REF: