sitecoresitecore-dms

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.


Solution

  • 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: