Preloading View Model Data into a Knockout Model (Without the extra JSON call) in ASP.Net MVC

I’ve recently been playing around with Knockout and working it in with to my MVC apps.  It dramatically simplifies some of the complexities of keeping an interface up to date when performing JavaScript changes.

One of the very first issues I ran into was, how do I load in some initial data from C#?  The advertised and I assume the easiest way is to just make an extra get JSON call.  But what if I just need a few values to populate a dropdown?  Say a list of States.  Personally I think it’s a waste of an extra JSON call when it can just be embedded in the page itself. 

So let’s take a look at the C# view model:

public class Viewmodel
{
     public IEnumerable States {get; set;}
}

public class State
{
     public string Abbr {get; set;}
     public string Name {get; set;}
}

And our knockout model:

function AppViewModel() {
    var self = this;
    self.states = ko.observableArray();
}

ko.applyBindings(new AppViewModel());

Our goals is to populate the self.states member with our list from the C# view model.  Sure you can do the following code:

function AppViewModel() {
    var self = this;
    self.states = ko.observableArray();
}

var model = ko.applyBindings(new AppViewModel());

// url that gets the state object in json format
var url = 'some url';
$getJSON(url, function(results) {
     $.each(results, function(item, index){
          model.states.push(item);
     });
});

But wouldn’t it nice if we could just initialize the array without having to go back to the server?  Especially for such a small list.  There are times when the above code makes sense.  Consider the following:

var depts = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model.States.Select(a => new { id= a.Abbr, name=a.Name })));

function AppViewModel() {
    var self = this;
    self.states = ko.observableArray(states);
}

ko.applyBindings(new AppViewModel());

(Yes it’s using Razor syntax, but it can just as easily use the older syntax).  The line of code essentially takes the array of states and creates the raw javascript array as if it was hard coded in the page, which in turn can be easily loaded into an observable array.  It works fantastically with small lists (and can with large lists, but consider load times before deciding which way to go.

That’s about it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s