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:
- The Sitecore fields being rendered out by the razor view are not editable in the Page Editor.
- I doubt very much that the
StandaloneRendering.cshtml
output will make it into the Sitecore HTML cache.
- The
Item
property in the @functions
block should be moved to some where so that it can be reused across multiple razor views.
- It's a non-standard approach. This may confuse some folks who expect to find an associated rendering item in Sitecore.