Created
September 10, 2013 16:44
-
-
Save andrewbranch/6512134 to your computer and use it in GitHub Desktop.
HtmlHelper to generate JavaScript object from C# object
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
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> | |
<%= Html.WriteToJavaScript(Model, "window.model") %> | |
</asp:Content> |
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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web; | |
using System.Web.Mvc; | |
using Newtonsoft.Json; | |
namespace ProjectName.Helpers { | |
public static class ScriptExtensions { | |
public static string WriteToJavaScript(this HtmlHelper helper, object Object, string variableName) { | |
var builder = new TagBuilder("script"); | |
builder.InnerHtml = String.Format("{0} = JSON.parse('{1}');", variableName, JsonConvert.SerializeObject(Object, Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, StringEscapeHandling = StringEscapeHandling.EscapeHtml })); | |
return builder.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment