MDM
MDM

Reputation: 927

Change Title and Add Facebook OG Meta in Razor

Blog posts for the 2sxc Blog App are not shared with proper titles by Facebook share buttons. Currently blog post Razor handles title-change with javascript. Facebook and search engines don't like that. As a result they end up getting the default title from the parent page. To fix I need to change page title via the C# Razor file "_Post Details.cshtml". Also adding og:title and og:image meta would be a bonus.

I can build meta easy enough:

// build facebook meta
HtmlMeta metaOGTitle = new HtmlMeta();
metaOGTitle.Attributes.Add("property", "og:title");    
metaOGTitle.Content = post.Title;
HtmlMeta metaOGImage = new HtmlMeta();
metaOGImage.Attributes.Add("property", "og:image");    
metaOGImage.Content = post.Image.ToLower();

The trick is getting a reference to the page header. I have looked at several old posts. I get a "cannot convert type 'System.Dynamic.DynamicObject' to 'DotNetNuke.Framework.CDefault" when trying this code from Chris Hammond:

DotNetNuke.Framework.CDefault tp = (DotNetNuke.Framework.CDefault)this.Page;
tp.Title = "This is my page title";

Using Page.Header or Page.FindControl("Head") leads to null reference exceptions.

Upvotes: 1

Views: 591

Answers (1)

MDM
MDM

Reputation: 927

OK Thanks to Birsky89 at https://gist.github.com/birksy89/c755fd83d0943b5ab94b and Pola Edward at Change Page Title in DNN Programatically from Razor I have been able to put together a reasonably succinct solution.

I added the code to the top of my "Post Details.cshtml" and it's working like a charm.

@using System.Web.UI.HtmlControls;

    // build facebook meta
    HtmlMeta metaOGTitle = new HtmlMeta();
    metaOGTitle.Attributes.Add("property", "og:title");    
    metaOGTitle.Content = post.Title;
    HtmlMeta metaOGImage = new HtmlMeta();
    metaOGImage.Attributes.Add("property", "og:image");    
    metaOGImage.Content = post.Image.ToLower();

    // change the title and add facebook meta      
    var pageObj = Context.CurrentHandler as Page;
    pageObj.Title = post.Title;
    pageObj.FindControl("Head").Controls.Add(metaOGTitle);
    pageObj.FindControl("Head").Controls.Add(metaOGImage);

Upvotes: 3

Related Questions