Old question, but I think I have a nice tidy solution for passing model data to a KO view model, in a reusable fashion. Note, I'm using require.js as well.
Add the HtmlHelper extension method, in .NET:
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace PROJECT.YOUR.EXTENSIONS.NAMESPACE {
public static class HtmlHelperJavascriptExtensions {
public static IHtmlString Serialize(this HtmlHelper helper, object obj) {
return helper.Raw(new JavaScriptSerializer().Serialize(obj));
}
}
}
Add the partial view, KnockoutJsBinderPartial (I've had to use aspx):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PROJECT.Views.Shared.KnockoutJsBinderViewData>" %>
<%@ Import Namespace="PROJECT.YOUR.EXTENSIONS.NAMESPACE" %>
<script type="text/javascript">
require(["Path/To/KnockoutJs", "<%= Model.ViewModelPath %>"], function (ko, ViewModel) {
ko.applyBindings(new ViewModel(<%= Html.Serialize(Model.InnerModel) %>));
});
</script>
The model referenced by that view is:
namespace PROJECT.Views.Shared {
public class KnockoutJsBinderViewData {
public object InnerModel { get; private set; }
public string ViewModelPath { get; private set; }
public KnockoutJsBinderViewData(object innerModel, string viewModelPath) {
InnerModel = innerModel;
ViewModelPath = viewModelPath;
}
}
}
Now, to wire up your .NET model to your knockout view model, all you need to do is:
<% Html.RenderPartial(
"~/Views/Shared/KnockoutJsBinderPartial.ascx",
new PROJECT.Views.Shared.KnockoutJsBinderViewData(
Model, // The model from your strongly typed MVC view
"Path/To/Knockout/ViewModel")); // The path to the Javascript file containing your view model
%>
Note, the Javascript file containing your view model SHOULD NOT call ko.applyBindings and should return the Constructor function for the view model. The constructor should take one argument - your JSON data for the model.