Skip to content

Instantly share code, notes, and snippets.

@erichexter
Created November 29, 2012 03:17
Show Gist options
  • Save erichexter/4166568 to your computer and use it in GitHub Desktop.
Save erichexter/4166568 to your computer and use it in GitHub Desktop.
Loading KnockoutJS viewmodels from a server side razor template.
Make sure to include the Mapping plugin in this page.
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script type="text/javascript">
$(function() {
var viewModel = ko.mapping.fromJS(@Html.Raw(Model.ToJson()));
ko.applyBindings(viewModel);
});
</script>
using System.IO;
using Newtonsoft.Json;
namespace UI.Models
{
public static class ObjectExtensions
{
public static string ToJson(this object obj)
{
JsonSerializer js = JsonSerializer.Create(new JsonSerializerSettings());
var jw = new StringWriter();
js.Serialize(jw, obj);
return jw.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment