Html Helper for sharing links to Facebook

Wed Jan 12 2011 by MarkP

Over the last few days I have been working on this site to try and improve it whilst I had some time and also to improve my knowledge of the MVC framework. I had a requirement to be able to share my articles with social networking sites such as Facebook. Facebook has a javascript library which simplifies the process of displaying and sharing specific urls or pages on Facebook. Further information and details can be found at the Facebook Share site.

ASP.NET MVC has many built in HtmlHelpers that makes the displaying Html controls simpler and cleaner on the View and reduces the code required especially when the code needs to be dynamically created based on the model or route values. With this in mind a HtmlHelper was created to display the "Share Facebook" button on the page:

  1. public static MvcHtmlString FacebookShare(this HtmlHelper html,string type, string controllerName,string actionName, object routeValues)
  2.         {
  3. var tag = new TagBuilder("a");
  4. tag.MergeAttribute("name", "fb_share");
  5.             
  6. if(!string.IsNullOrEmpty(type))
  7. tag.MergeAttribute("type", type);
  8.  
  9. RequestContext ctx = html.ViewContext.RequestContext;
  10. UrlHelper urlHelper = new UrlHelper(ctx);
  11. tag.MergeAttribute("share_url", urlHelper.Action(actionName, controllerName, new RouteValueDictionary(routeValues), ctx.HttpContext.Request.Url.Scheme, ctx.HttpContext.Request.Url.Host));
  12. return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
  13.         }

This is displayed on the View using the following syntax (using Razor View Engine):

  1. @Html.FacebookShare("Facebook button type", "Controller", "Action", new {RouteValues})

At present the HtmlHelper is limited to Route Values only but could easily be extended to use optional parameters, such as Html attributes or the direct page link if required. The key requirement was to be able to pass in Route Values only and to be able to automatically create the link using MVC's built in methods such as the UrlHelper object.

Update
For Asp.NET MVC 3.0 you would use HtmlString rather than MvcHtmlString and return a new HtmlString(string value) rather than the static Create method exposed in the MvcHtmlString object.

Tags: MVC   Facebook  

Comments

Required fields are marked with required

The form could not be submitted please check the errors and resend:
Post a Comment