KnockoutJS & ASP.NET Mvc Partial View Loading

Recently I’ve needed to dynamically load ‘partial views’ that are bound to KnockoutJS view models.  The application is a single page app approach, composite application where I’m loading a particular view.

Retrieving the ‘partialView’ is rather simple with ASP.NET Mvc:

image

This is rather straightforward.   I make the call to retrieve the template with a jQuery ajax call:

image

I create my viewmodel, and my viewmodel has a property with the partialViewName defined – ie. self.partialViewName = “_SomePartialView”;

This works very well so far – I have some caching of the html partial, although I might remove this and just takes a more server side ‘get’ ‘varybyparam’ caching on the controller action.

Previously I had an approach like this:

<div data-bind=”with: myViewModel”>
@Html.Partial(“_SomePartialView”)
</div>

Which I still believe works good for one or two scenarios – but the number of viewmodel objects (I have 20+ views here getting loaded) let me change my approach to more of a ‘load on demand’.  I’m pretty happy with this!

Update: one of my concerns that I meant to research and apply here is the impact of loading vm’s to the same dom node with applyBinding and memory leaks.

A good response to this on stack overflow: http://stackoverflow.com/questions/10048485/how-to-clear-remove-observable-bindings-in-knockout-js/10049722#10049722

So what I do for this is use the ko.cleanNode prior to re-applying this binding to the same node:

image

Advertisements

2 thoughts on “KnockoutJS & ASP.NET Mvc Partial View Loading

  1. Wow this is exactly what we just did. Your code is really similar. We left the Html.Partial() code so we can either lazy load or eager load depending on whether or not we think that the view will be accessed a lot. We are writing a SPA so we cache the view and we use sammy.js to navigate around without having to go to the server but maintaining the browsers back button.

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