2
votes

My terminology might be slightly off as I am new to Sitecore mvc. I am trying to hardcode a view rendering with a hard coded datasource (I have to do it this way for other requirements) This view rendering has placeholders that are dynamically set and then personalized.

How can I trigger the ViewRendering on an item?

I've tried ItemRendering, but it doesn't seem to be picking up the stuff set up in the PageEditor.

* To be clear, the helpful posts below have the rendering working, but we do not seem to be getting the personalized datasources. *

2
I leaning toward removing the static view, moving the custom controller rules into the personalization engine, and then setting it all up in the page editor using the personalization engine. - Rob Allen

2 Answers

4
votes

I believe this is what you're after:

Item item = /* think you already have this */;

// Setup
var rendering = new Sitecore.Mvc.Presentation.Rendering {
  RenderingType = "Item",
  Renderer = new Sitecore.Mvc.Presentation.ItemRenderer.ItemRenderer {
    Item = item
  }
};
rendering["DataSource"] = item.ID.ToString();

// Execution
var writer = new System.IO.StringWriter();
var args = new Sitecore.Mvc.Pipelines.Response.RenderRendering(rendering, writer);
Sitecore.Mvc.Pipelines.PipelineService.Get().RunPipeline("mvc.renderRendering", args);

// Your result:
var html = writer.ToString();
1
votes

You can statically bind a View Rendering using the Rendering() method of the Sitecore HTML Helper. This also works for Controller Renderings using the same method.

@Html.Sitecore().Rendering("<rendering item id>")

This method accepts an anonymous object for passing in parameters, such as the Datasource and caching options.

@Html.Sitecore().Rendering("<rendering item id>", new { DataSource = "<datasource item id>", Cacheable = true, Cache_VaryByData = true })

In your view rendering, I am assuming you have a placeholder defined along with the appropriate placeholder settings in Sitecore (If not, feel free to comment with more detail and I will update my answer).

@Html.Sitecore().Placeholder("my-placeholder")

In this case, "my-placeholder" will be handled like any other placeholder, so you will be able to add and personalize components within it from the Page Editor.