Using this article posted on CodeProject.com, "Using KnockoutJS in your ASP.NET applications" as a guide I am attempting to create a reusable, data-loaded drop down list using ASP.NET 3.5 Web Forms, but that leverages KnockoutJS for client-side data-binding. Multiple, independent instances of this drop down should be able to live independently in the same page.
So far the CodeProject.com post has been invaluable in directing me on how to set things up and I am successfully passing the updated ViewModel data back and forth between the server and client as a JSON string and converting it to and from an object (both on the server and client). What I am hanging up on is what should be the simple part; binding the ViewModel to the drop down list!
So I begin by loading the JSON string into a hidden field. It includes a list of Regions and a single SelectedRegion.
<input type="hidden" id="ddlRegionKO_hdnRegionListVMStorage" value="{"Regions":[{"RegionName":"Mid Atlantic USA","RegionId":2},{"RegionName":"Mid West USA","RegionId":10},{"RegionName":"North Central USA","RegionId":5},{"RegionName":"North East USA","RegionId":1},{"RegionName":"North West USA","RegionId":7},{"RegionName":"Other","RegionId":9},{"RegionName":"South Central USA","RegionId":6},{"RegionName":"South East USA","RegionId":3},{"RegionName":"South West USA","RegionId":8}],"SelectedRegion":{"RegionName":"North Central USA","RegionId":5}}" />
I then run convert this string into a Javascript Object using the ko.utils.parseJson()
function.
var stringViewModel = document.getElementById("ddlRegionKO_hdnRegionListVMStorage").value;
var ddlRegionKO_pnlRegionDDLContainer_ViewModel = ko.utils.parseJson(stringViewModel);
Then I convert the property definitions into ko.observable
and ko.observableArray
methods (this is one of those sections that will be need to be refactored, but as a proof of concept it suffices).
//
// Convert all the model properties to KO Propety/Methods
for (var propertyName in ddlRegionKO_pnlRegionDDLContainer_ViewModel) {
switch(propertyName.toUpperCase())
{
//
// Multiple Region objects are stored as an array in the regions property.
case "REGIONS":
ddlRegionKO_pnlRegionDDLContainer_ViewModel[propertyName] = ko.observableArray(ddlRegionKO_pnlRegionDDLContainer_ViewModel[propertyName]);
break;
//
// Only a single region may be selected at any time.
case "SELECTEDREGION":
ddlRegionKO_pnlRegionDDLContainer_ViewModel[propertyName] = ko.observable(ddlRegionKO_pnlRegionDDLContainer_ViewModel[propertyName]);
break;
};
};
Given this, I would expect the drop down list to be populated and the SelectedRegion selected when the applyBindings
method is called ...
ko.applyBindings(ddlRegionKO_pnlRegionDDLContainer_ViewModel);
I have put this all together at JSFiddle ... here ... I suspect that I may be overlooking something but I cannot see what it might be. Everything looks right to me.
If anybody can see something that I am overlooking I would be extremely grateful!
Thanks,
-g