Skip to content

Instantly share code, notes, and snippets.

@bbg
Forked from EdCharbeneau/AsJson.cshtml
Created February 15, 2021 08:26
Show Gist options
  • Save bbg/845ce2805eb5bc7e75ccbf910daeeba4 to your computer and use it in GitHub Desktop.
Save bbg/845ce2805eb5bc7e75ccbf910daeeba4 to your computer and use it in GitHub Desktop.
Turn any Umbraco content into a JSON object by using a Razor template
@*Experimental, I'm still fairly new to Umbraco there could be an API avialbe for this already.
This was inspired by http://cultiv.nl/blog/razor-vs-base-to-output-json-in-umbraco/
If there is a better way please let me know via twitter @EdCharbeneau
Add this template to your Umbraco site and any content can be called via Ajax using
/mySite/contentPath/?alttemplate=AsJson
Return value will be { propertyAlias : value }
Ex: { "personAlias" : "John Doe", "id" : 1002 }
*@
@using Newtonsoft.Json;
@using System.Dynamic;
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
Layout = null;
Response.ContentType = "application/json";
dynamic exObj = new ExpandoObject();
var dictionary = exObj as IDictionary<string, object>;
Model.Content.Properties.ForEach(p => dictionary[p.PropertyTypeAlias] = p.Value);
}
@Html.Raw(JsonConvert.SerializeObject(exObj))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment