Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sitecore Personalize is not working

I create a simple demo site for DMS function of Sitecore. In sitecore content, I created this structure:

Home
|-Personalize
..|-HomeView1
..|-HomeView2

HomeView1, HomeView2 and Home have the same template, which contains only one Field: Display Text

Now I create Personalize for home page, set rule for it. The rule is current month is August and point the Personalize Content to HomeView1. When I do preview the content doesn't change into text of HomeView1. Here is my source code:

public partial class HomePage : System.Web.UI.UserControl
{
    protected Item currentItem;
    protected void Page_Load(object sender, EventArgs e)
    {
        currentItem = Sitecore.Context.Item;
    }
}

And this what I bound on Home page

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HomePage.ascx.cs" Inherits="DMSDemo.sublayouts.HomePage" %>
<div><%= currentItem["Display Text"].ToString() %></div>

I wonder why Sitecore.Context.Item will not return the correct item (HomeView2) when the personalize rule is applied?

Please give me some advise. Thanks in advance.

like image 786
Truong Anh Tuan Avatar asked Dec 02 '25 05:12

Truong Anh Tuan


1 Answers

The context item doesn't change when you personalize, the sublayout's datasource does. So you should set currentItem to the datasource.

Here's some common code to get the datasource which I copy/pasted from Matthew Dresser's blog:

var sublayout = this.Parent as Sitecore.Web.UI.WebControls.Sublayout;
if (sublayout != null)
{
    Guid dataSourceId;
    Sitecore.Data.Items.Item dataSource;
    if (Guid.TryParse(sublayout.DataSource, out dataSourceId))
    {
        dataSource = Sitecore.Context.Database.GetItem(new ID(dataSourceId));
    }
    else
    {
        dataSource = Sitecore.Context.Database.GetItem(sublayout.DataSource);
    }
}

Some other points:

  • In general, it's good practice to avoid the use of the context item
  • There is no requirement for your page item (Home) to be the same template has the datasource items.
  • I don't think personalization works in preview mode, but you can check it in edit mode.
like image 200
Martin Davies Avatar answered Dec 04 '25 20:12

Martin Davies