This is a quick tip for allowing a single service (Web Api Controller, MVC Route etc) to programmatically register goals against any page.
Typically when using the Sitecore DMS to register goals through code, the most common approach is to use the Tracker class to register a goal on the current page, as such;
//Create the record that needs to be stored (the goal)
VisitorDataSet.PageEventsRow pageEventsRow = Tracker.CurrentPage.Register(goal);
//Add any data you like, which will be stored with the PageEvent
pageEventsRow.Data = eventMessage;
pageEventsRow.ItemId = goalItem.ID.ToGuid();
//Submit the goal
Tracker.Submit();
The issue with this is that it registers a goal against the current page only.
In some scenarios you may wish to register goals against other pages. For instance if you would like to set up a generic MVC/Web API route to register a goal from client side, accepting any page.
To do this, you can use the PagesRow class (the class type for the Tracker.CurrentPage object) from the VisitorDataSet to register the goal.
//Getting the current page into PagesRow
VisitorDataSet.PagesRow page = Tracker.Visitor.CurrentVisit.CurrentPage;
//Override items as required
page.ItemId = tmpItemId.ToGuid();
page.PageId = tmpItemId.ToGuid();
page.Url = "/Articles/Custom-Field-for-Task-Schedule";
var pageEventData = new PageEventData(goalName)
{
ItemId = tmpItemId.ToGuid(),
DataKey = goalName,
Data = "/Articles/Custom-Field-for-Task-Schedule",
Text = targetItem.Name
};
//Register via page
page.Register(pageEventData);
This example uses the CurrentPage object to instantiate a PagesRow object, which is then overridden with the required values. I then create a standard MVC route to this method. My example looks like this;
routes.MapRoute(
"RecordGoal", // Route name
"rest/goal/{goalName}/{itemId}", // URL with parameters
new
{
action = "RecordGoal",
controller = "MarkettingService",
});
I can now call this route from any page client side, and simply pass the goal name and the page I wish to register it against. Now in the Latest Visits report, I can see my goal recorded against the correct page:











