RSS

Tag Archives: twitter

Twitter Html Helper – MVC 3

Twitter Logo
let us code a ‘Latest Tweets’ HTML Helper.

Create a new MVC 3 app and add a new module the following code

Twitter HTML Helper


Public Module MyExtensions

    Function Twitter(htmlHelper As HtmlHelper,
                     screenName As String,
                     Optional maxRows As Integer = 5) As MvcHtmlString

        'Construct the URL to call the Twitter API
        Dim twitterUrl = String.Format("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name={0}&count={1}",
                                       screenName, maxRows)

        'Get the Data as XML
        Dim rss = XDocument.Load(twitterUrl)


'Create a ul tag
Dim ulTag = New TagBuilder("ul")

'Loop each tweet

Dim tweets = rss.Descendants("status").Select(Function(x) x.Element("text").Value).ToList
For Each tweet In tweets

'Create a li tag
 ulTag.InnerHtml += New TagBuilder("li") With {.InnerHtml = tweet}.ToString

 Next

 Return MvcHtmlString.Create(ulTag.ToString(TagRenderMode.Normal))

 End Function

End Module

notice that the module marked as Public.

what we are doing here is Loading the XML feed for the twitter user specified, then create an unordered list, with the tweets as content

to use this extension method you have to import the namespace, so in your web.config file go to the <namespaces> section under the <pages> tag and add the following

add <namespace=”MyProject.MyExtensions” />

the namespace MyProject depends on your project name, and can be found under My Project > Application Tab > Root Namespace.

use this HTML Helper simply by typing

@Html.Twitter(“username”)

Summary

shown here is a way to interact with public API’s using XML documents, and integrating that with MVC’s Html Helper

Advertisements
 
Leave a comment

Posted by on 10, Aug 2011 in .NET, ASP.NET

 

Tags: , , , ,