Adding custom meta tags from Sitefinity MVC widget

Sitefinity CMS provides an excellent option to develop a CMS page either as a Pure MVC, or Webform based or Hybrid.

Hybrid pages are an excellent choice, that allows you to enjoy the pros of both MVC and webform worlds. But if you are concerned about the generated HTML markups and want to try Pure MVC.

Watch Out! Pure MVC is not a normal MVC

Because

  1. Sitefinity allows multiple controller in a single page foot-in-mouth [MvcProxyControllers are used]
  2. You can't expect to see the ViewBag and ViewData being shared between multiple controls or controllers
  3. Trying to add the meta tags through a @section tag will leave you mad. The sections that you see on the default layout template like @section("top"), @section("bottom"), @section("head") are just for injecting the scripts and styles at the desired places.

My requirement was to append the OpenGraphs properties to the page from a custom mvc widget. I was completely mad that the normal MVC way of doing things ended up in disappointment.

So did I find a solution ? Yes I did.

Deep down in the Sitefinity forum thread, following code snippet was shared by a Sitefinity support staff. Solution totally looks in a non MVC way. but lucky to see it working.

private void AddMetaProperties(string property, string content)
{
   HtmlMeta hm = new HtmlMeta();
   hm.Attributes.Add("property", property);
   hm.Content = content;
   ((System.Web.UI.Page)this.HttpContext.CurrentHandler).Header.Controls.Add(hm);
}

Hope this information has helped you. Share you thoughts!