Updating the title within a SPItemEventReceiver with AfterProperties
Recently I had a problem setting the title field of a Page within the pages library. My requirement was to set the title with the value from the PageTitle field of the current item.
An ItemEventReceiver, which is executed synchronously to prevent save conflict exception or problems with published items, was supposed to do exactly that. But when I set the title property of the item via AfterProperties, the value did not get stored. I tried other fields, and they got written to the item just fine. After some trial-and-error and consulting the MSDN I found a solution.
The ItemEventReceiver needs to update the vti_title field instead. This field exists on a SPFile. And since a Page is a SPFile, you’ll need to modify that field instead.
public override void ItemAdding(SPItemEventProperties properties) { base.ItemAdding(properties); UpdateTitleField(properties); } public override void ItemUpdating(SPItemEventProperties properties) { base.ItemUpdating(properties); UpdateTitleField(properties); } /// <summary> /// Set title from PageTitle /// </summary> /// <param name="properties"></param> private void UpdateTitleField(SPItemEventProperties properties) { var title = Convert.ToString(properties.AfterProperties["PageTitle"]); if (!string.IsNullOrEmpty(title) && properties.List.Fields.ContainsFieldWithStaticName("vti_title")) properties.AfterProperties["vti_title"] = title; }
With this code, the title of my page was changed as supposed to.