Skip to content

Instantly share code, notes, and snippets.

@rymoore99
Created February 19, 2014 13:08
Show Gist options
  • Save rymoore99/9091605 to your computer and use it in GitHub Desktop.
Save rymoore99/9091605 to your computer and use it in GitHub Desktop.
Helper method for serializing objects to JSON in Razor Views
public static class HtmlHelperExtensions
{
public static MvcHtmlString SerializeToJson(this HtmlHelper helper, string javascriptVariableName,
object objectToSerialize)
{
if (javascriptVariableName.Contains(" "))
throw new Exception("Invalid JS variable name");
return
MvcHtmlString.Create(String.Format("var {0}={1};", javascriptVariableName,
Json.Encode(objectToSerialize)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment