GeekZilla
Rendering a Twitter Tweet with Razor and C# MVC4
Using Linq to Twitter I pulled a feed which I needed to render on a website. The body of the tweet was something like :
RT @KristyT: The Floppy Disk means Save, and 14 other old people Icons that don't make sense anymore http://t.co/57vmXBY7Pc via @shanselman
I decided to write a Helper Extension for Razor so I could render the tweet like this:
<div class="tweet"> <a href="http://twitter.com/@item.ScreenName"><img src="@item.ImageUrl" /></a> <div class="tweettext">@Html.RenderTweet(item.Tweet)</div> <div class="clear"></div> </div>
The code for the Helper Extension
The helper extension was simple.. basically using RegEx to match on screen names, hash tags and URLs
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Security; namespace kwiboo2013.HtmlExtensions { public static class GeekZillaHtmlHelperExtensions { public static MvcHtmlString RenderTweet(this HtmlHelper helper, string value) { value = Regex.Replace(value, @"[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+", "<a href=\"$0\">$0</a>"); value = Regex.Replace(value, @"(?:[@]+)([A-Za-z0-9-_]+)", "<a href=\"http://twitter.com/$1\">@$1</a>"); value = Regex.Replace(value, @"(?:[#]+)([A-Za-z0-9-_]+)", "<a href=\"https://twitter.com/search?q=%23$1\">#$1</a>"); return new MvcHtmlString(value); } } }
The web.config entry
You need to register your namespace in the web.config in the Views folder see kwiboo2013.HtmlExtensions below:
<system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Optimization" /> <add namespace="System.Web.Routing" /> <add namespace="kwiboo2013.HtmlExtensions" /> </namespaces> </pages> </system.web.webPages.razor>
Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.
Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.