Convert Sitecore item into RenderingModel for MVC 2

Following code helps to add in item extension class or helper class to convert Sitecore item into Sitecore.Mvc.Presentation.RenderingModel. I have added code and extended in local Habitat Foundation project.

        public static RenderingModel AsRenderingModel(this Item item)
        {
            RenderingContext renderingContext = RenderingContext.CurrentOrNull;
            Assert.IsNotNull(renderingContext, "RendreingContext is null");

            // get rendering
            var rendering = renderingContext.Rendering;
            Assert.IsNotNull(rendering, "Rendreing is null");

            // set the current rendering item
            rendering.Item = item;

            // create and intialise the rendering model
            RenderingModel renderingModel = new RenderingModel();
            renderingModel.Initialize(rendering);
            
            // return the rendering model
            return renderingModel;
        }

Let me know if you have any trouble.

Cheers

2 thoughts on “Convert Sitecore item into RenderingModel for MVC

  1. Reply Stefan Sluijter Feb 3,2017 11:06 am

    Pretty straight forward, Thanks for sharing! 🙂

  2. Reply Chad Oct 24,2017 9:49 pm

    Very nice, thanks.

Leave a Reply