Created
November 29, 2012 03:17
-
-
Save erichexter/4166568 to your computer and use it in GitHub Desktop.
Loading KnockoutJS viewmodels from a server side razor template.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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