Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static View Renderings in Sitecore 6.6

I was wondering if there was any way to statically call a View Rendering similarly to how you would call a sublayout using the following web forms code:

<sc:Sublayout Path="~/sublayouts/samplesublayouts.ascx" DataSource="SomeItemId" runat="server" />

I've tried doing this:

@Html.Sitecore().ViewRendering("~/renderings/samplerendering.cshtml", new { DataSource= "SomeItemId"})

But I can't strongly type the view rendering unless I also create the rendering item in sitecore and the also create the model item in sitecore because I'll receive and error. I'd like to know if there is a similarly simple manner I could use with MVC for statically typing internal renderers.

like image 585
IAreATomKs Avatar asked Jun 27 '13 20:06

IAreATomKs


1 Answers

The approach shown below allows razor views to be statically bound to presentation items without creating rendering items.

In the layout.cshtml file statically bind a razor view that doesn't have a View Rendering presentation item in Sitecore and specify a DataSource item:

@Html.Sitecore().ViewRendering("/views/StandaloneRendering.cshtml", new { DataSource = "/sitecore/content/Home/My Datasource Item" })

The StandaloneRendering.cshtml razor view looks like this:

@using Sitecore.Mvc.Presentation
@model RenderingModel

@functions
{
    public Sitecore.Data.Items.Item Item 
    { 
        get
        {
            var item = Sitecore.Context.Item;

            if (!string.IsNullOrEmpty(Model.Rendering.DataSource))
            {
                item = Sitecore.Context.Database.GetItem(Model.Rendering.DataSource);
            }
            return item;
        }
    }
}   

<p>Item  Name: @Model.PageItem.Name</p>    
<p>Datasource Path: @Model.Rendering.DataSource</p>    
<p>Datasource Item Name: @Item.Name</p>
<p>Datasource Item Path: @Item.Paths.FullPath</p>
<p>Datasource Item Template: @Item.TemplateName</p>

The following gets output on the page:

Item Name: Home

Datasource Path: /sitecore/content/Home/My Datasource Item

Datasource Item Name: My Datasource Item

Datasource Item Path: /sitecore/content/Home/My Datasource Item

Datasource Item Template: Sample Item

A couple of things to be aware of when doing this:

  1. The Sitecore fields being rendered out by the razor view are not editable in the Page Editor.
  2. I doubt very much that the StandaloneRendering.cshtml output will make it into the Sitecore HTML cache.
  3. The Item property in the @functions block should be moved to some where so that it can be reused across multiple razor views.
  4. It's a non-standard approach. This may confuse some folks who expect to find an associated rendering item in Sitecore.
like image 84
Kevin Obee Avatar answered Oct 01 '22 19:10

Kevin Obee