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><br /> Your country:
<asp:DropDownList ID="ddlCountries" runat="server" data-bind="options: countryModel.countries, optionsValue: 'CountryID', optionsText: 'CountryName', optionsCaption: 'Choose...'"><br /> </asp:DropDownList><br /> </p><br /> <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:
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.
The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.