Adding Facebook Open Graph Tags to an MVC Application

Posted by amaniar on Geeks with Blogs See other posts from Geeks with Blogs or by amaniar
Published on Tue, 28 Aug 2012 14:13:45 GMT Indexed on 2012/08/28 21:41 UTC
Read the original article Hit count: 219

Filed under:

If you have any kind of share functionality within your application it’s a good practice to add
the basic Facebook open graph tags to the header of all pages.

For an MVC application this can be as simple as adding these tags to the Head section of the Layouts file.

<head>
    <title>@ViewBag.Title</title>
    <meta property="og:title" content="@ViewBag.FacebookTitle" />
    <meta property="og:type" content="website"/>
    <meta property="og:url" content="@ViewBag.FacebookUrl"/>
    <meta property="og:image" content="@ViewBag.FacebookImage"/>
    <meta property="og:site_name" content="Site Name"/>
    <meta property="og:description" content="@ViewBag.FacebookDescription"/>
</head> 
 
These ViewBag properties can then be populated from any action:
 
private ActionResult MyAction()
    {
        ViewBag.FacebookDescription = "My Actions Description";
        ViewBag.FacebookUrl = "My Full Url";
        ViewBag.FacebookTitle = "My Actions Title";
        ViewBag.FacebookImage = "My Actions Social Image";
        ....
    }
 
You might want to populate these ViewBag properties with default values when the actions don’t populate them. 
This can be done in 2 places.
 
1. In the Layout itself. (check the ViewBag properties and set them if they are empty)
 
@{
    ViewBag.FacebookTitle = ViewBag.FacebookTitle ?? "My Default Title";    
ViewBag.FacebookUrl = ViewBag.FacebookUrl ?? HttpContext.Current.Request.RawUrl; ViewBag.FacebookImage = ViewBag.FacebookImage ?? "http://www.mysite.com/images/logo_main.png"; ViewBag.FacebookDescription = ViewBag.FacebookDescription ?? "My Default Description"; }
 
2. Create an action filter and add it to all Controllers or your base controller.
 
public class FacebookActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var viewBag = filterContext.Controller.ViewBag;

            viewBag.FacebookDescription = "My Actions Description";
            viewBag.FacebookUrl = "My Full Url";
            viewBag.FacebookTitle = "My Actions Title";
            viewBag.FacebookImage = "My Actions Social Image";

            base.OnActionExecuting(filterContext);
        }
   }
 
Add attribute to your BaseController.
 
[FacebookActionFilter]
public class HomeController : Controller
 {
  ....
 }
 

© Geeks with Blogs or respective owner