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.
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:
StandaloneRendering.cshtml
output will make it into the Sitecore HTML cache.Item
property in the @functions
block should be moved to some where so that it can be reused across multiple razor views.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With