Skip to content

Instantly share code, notes, and snippets.

@andrewbranch
Created September 10, 2013 16:44
Show Gist options
  • Save andrewbranch/6512134 to your computer and use it in GitHub Desktop.
Save andrewbranch/6512134 to your computer and use it in GitHub Desktop.
HtmlHelper to generate JavaScript object from C# object
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<%= Html.WriteToJavaScript(Model, "window.model") %>
</asp:Content>
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