Search code examples
c#umbracoumbraco8

Rendering Grid Layout From JToken in Umbraco 8


I have created a DocType MyDocType.

DocTypeGridEditor requires it to be of type ElementType, therefore, I checked it to be of that type in the Umbraco Backoffice.

It contains one property: GridLayout, i.e:

public Newtonsoft.Json.Linq.JToken MyGrid => this.Value<Newtonsoft.Json.Linq.JToken>("myGrid");

And in my cshtml I would like to render it but

@Html.GetGridHtml()

requires first parameter to be of type IPublishedContent. I am using UmbracoViewPage for the template.

Is there a way to render its content? Is it even possible to render Grid from ElementModel?


Solution

  • I have managed to resolve this issue by creating my own extension to the HtmlHelper. Here is a snippet:

    public static class GridLayoutExtensions
    {
        public static MvcHtmlString GetGridHtml(this HtmlHelper html, IPublishedElement publishedElement, string propertyAlias)
        {
            if (propertyAlias == null)
            {
                return new MvcHtmlString("");
            }
    
            var model = publishedElement
                .GetProperty(propertyAlias)
                .GetValue();
    
            return html.Partial("Grid/bootstrap3", model);
        }
    }
    

    And now all I need to do is to use it by passing an element which contains GridLayout property.

    @Html.GetGridHtml2(Model.MyDocType, "gridLayout")
    

    And it works flawlessly.