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 via @shanselman

I decided to write a Helper Extension for Razor so I could render the tweet like this:

<div class="tweet">
    <a href=""><img src="@item.ImageUrl" /></a>
    <div class="tweettext">@Html.RenderTweet(item.Tweet)</div>
    <div class="clear"></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=\"$1\">@$1</a>");
            value = Regex.Replace(value, @"(?:[#]+)([A-Za-z0-9-_]+)""<a href=\"$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:

  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <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" />
Author Paul Hayman

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 ( and is also the creator of GeekZilla.

Add Comment


Your comment has been received and will be shown once it passes moderation.