Using MVC and jQuery to build a NewsTicker

Scott Guthrie tweeted a link to an article by Scott Mitchell. In it Scott wrote a handy news ticker in Asp.Net . And he wrote it in VB. I recommend going to read it before doing anything else.

It is a handy little example and a very good demonstration of jQuery in action. I actually first thought of using it in The Feedreader. Of course if I wanted to do that I’d have to re-write it as an MVC application rather than an ASP.Net website.

This is a nice academic exercise on moving from ASP.Met to MVC.

So lets get cracking.

Groundwork

So. We begin by creating an empty MVC2 project.

Actually, we began when we read Scott article. Its important to understand what Scotts trying toacomplish and how Scotts code works, before we shamelessly copy it.

The first thing you are going to want to do is make sure that Scotts’ ticker.js and jquery-1.4.4.min.js are in your MVC Scripts folder and included in the project. Also, you’ll want to copy Scott’s css files across. I put them in a folder called Styles and made sure it was included in the project.

Now, we need a Masterpage before we can create any Views. So add one in Views/Shared. We are shamelessly copying Scotts example in every detail. So go ahead and copy the markup in Scotts example and paste it into the your masterpage. You’ll want to change the script and css paths accordingly.

[sourcecode language="html"] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">;

<html xmlns="http://www.w3.org/1999/xhtml">; <head id="Head1" runat="server"> <title>Untitled Page</title> <script type="text/javascript" src="../../Scripts/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="../../Scripts/ticker.js"></script> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> <link href="../../Styles/sinorcaish-screen.css" rel="stylesheet" type="text/css" /> <link href="../../Styles/CustomStyles.css" rel="stylesheet" type="text/css" /> <link href="../../Styles/NewsTicker.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <!-- ======== Header ======== --> <div id="header"> <div class="left"> News Ticker Demo
</div> <div class="right"> <%=DateTime.Now.ToShortDateString()%> </div> <div class="subheader"> <em>News me!</em> </div> </div>

<!-- ======== Left Sidebar ======== --> <div id="sidebar"> <div> <ul> <li><%: Html.ActionLink("Simple Ticker Demo", "Simple","Home")%></li> <li><%: Html.ActionLink("Dynamic Ticker Demo", "Dynamic","Home")%></li> </ul> </div> </div>

<!-- ======== Main Content ======== --> <div id="main"> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

</asp:ContentPlaceHolder> </div>

<!-- ======== Footer ======== -->

<div id="footer"> ASP.NET application designed by <a href="http://www.4guysfromrolla.com/ScottMitchell.shtml">Scott Mitchell</a>.
Website design by <a href="mailto:J.Zaitseff@zap.org.au">John Zaitseff</a>, and available
at <a href="http://www.opendesigns.org/preview/?template=1700">OpenDesigns.org</a>;.
</div>

</form> </body> </html> [/sourcecode]

Remember to change the links in the sidebar to ActionLinks.

Controllers

The next thing we need to do is to write a Controller. Typically the first controller in any MVC application is the home controller.

So go ahead and create one, adding three ActionResult methods: Index, Simple and Dynamic.

[sourcecode language="csharp"] public class HomeController : Controller
{ // // GET: /Home/

public ActionResult Index()
{ return View();
} public ActionResult Simple()
{ return View();
} public ActionResult Dynamic()
{ return View();
} } [/sourcecode]

At this point, create a View for Index and copy the HTML from Default.aspx and stick it in the content control thats been created in the view.
Then, add an empty view for the Simple controller. Since this is straightforward HTML, we simply copy the contents of both ContentPlaceHolders in Simple.aspx into the two that have been created for us in the view

[sourcecode language="html"] <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

<h2>Simple News Ticker Demo</h2> <p> This demo shows two simple news tickers. Each news ticker has the same hard-coded news items. The
first one shows only the body of each news item, one at a time; the second one shows the headline,
body, and published date of each news item and shows three at a time.
</p>

<h3>One Row News Ticker</h3> <div class="ticker stretched"> <ul id="latestNews1"> <li> <div class="body">Politician Joe Smith has assembled a news conference for this afternoon to apologize for some indiscretion he had. This is Mr. Smith's third such "apology press conference" this year.</div>
</li> <li> <div class="body">Did you know that you can play the fun (and addictive!) board game Axis &amp; Allies online? Head on over to <a target="blank" href="http://gamesbyemail.com/Games/WW2">http://gamesbyemail.com/Games/WW2</a>;
and give it a whirl!</div>
</li> <li> <div class="body">A recent study by some doctors somewhere showed a strong correlation between unhealthy eating and unheathly people. More studies are to be performed to verify these findings.</div>
</li> <li> <div class="body">This just in - ASP.NET is awesome! jQuery is not so bad, either. In fact, most technologies are pretty darn cool. For more information, see <a href="http://www.4guysfromrolla.com/"; target="
blank">4GuysFromRolla.com</a>.</div>
</li> <li> <div class="body">Last night the local sports team won a convincing victory over their hated rivals. After the game there was much jubilation.</div>
</li> <li> <div class="body">Visit my blog. Please. You can find it at <a href="http://scottonwriting.net/sowblog/">ScottOnWriting.NET</a>.</div>; </li> </ul> </div>

<h3>Three Rows News Ticker</h3> <div class="ticker threeRows medium"> <ul id="latestNews3"> <li> <div class="header">Politician schedules news conference</div> <div class="body">Politician Joe Smith has assembled a news conference for this afternoon to apologize for some indiscretion he had. This is Mr. Smith's third such "apology press conference" this year.</div>
<div class="footer">Published @ 8:30 AM</div> </li> <li> <div class="header">Play Axis &amp; Allies Online!</div> <div class="body">Did you know that you can play the fun (and addictive!) board game Axis &amp; Allies online? Head on over to <a target="blank" href="http://gamesbyemail.com/Games/WW2">http://gamesbyemail.com/Games/WW2</a>;
and give it a whirl!</div>
<div class="footer">Published @ 8:38 AM</div> </li> <li> <div class="header">Study links unhealthy food to unhealthy people</div> <div class="body">A recent study by some doctors somewhere showed a strong correlation between unhealthy eating and unheathy people. More studies are to be performed to verify these findings.</div>
<div class="footer">Published @ 9:00 AM</div> </li> <li> <div class="header">ASP.NET is awesome!</div> <div class="body">This just in - ASP.NET is awesome! jQuery is not so bad, either. In fact, most technologies are pretty darn cool. For more information, see <a href="http://www.4guysfromrolla.com/"; target="
blank">4GuysFromRolla.com</a>.</div>
<div class="footer">Published @ 9:09 AM</div> </li> <li> <div class="header">Local sports team wins</div> <div class="body">Last night the local sports team won a convincing victory over their hated rivals. After the game there was much jubilation.</div>
<div class="footer">Published @ 9:35 AM</div> </li> <li> <div class="header">Read my blog</div> <div class="body">Please. You can find it at <a href="http://scottonwriting.net/sowblog/">ScottOnWriting.NET</a>.</div>; <div class="footer">Published @ 10:30 AM</div> </li> </ul> </div>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server"> <script type="text/javascript"> $(document).ready(function () { startTicker('#latestNews1', 1, 5000);
startTicker('#latestNews3', 3, 5000);
}); </script> </asp:Content> [/sourcecode]

Note the javascript in the “head” ContentPlaceHolder. This fires as soon as the page as finished rendering. Scott has more details about it in his article.

Model

Now, this is the hard part.

Scott Mitchells’ example used an ASP ListView control. If you’re writing ASP.Net code a listview is the easiest way to accomplish what we’re trying to do.  You’ll notice as well that Scott passes the contents of SyndicationFeed.Items directly to the databound control. Now there is most probably a way of using Scott’s code directly in an MVC view. However, for the purposes of convenience we’ll dispense with the ListView and iterate over items ourselves.

There is also the issue of the Formatting of the items. You’ll notice that the ItemTemplate in Scotts’ code calls FormatSummary and FormatPubDate from the HTML. Because of the separation between code and HTML in MVC we can’t do that.

The solution to both of these “problems” is to do things ourselves. The M in MVC stands for model. So we need a model before we go any further. The two pieces of data we need are contained in the Summary and the PublishDate fields of the SyndicationItems. So this is what our model looks like:

[sourcecode language="csharp"] public class Model
{ public String Title { get; set; }
public string Date { get; set; }
} [/sourcecode]

FormatSummary and Format PubDate, obviously need to be part of  the HomeController class:

[sourcecode language="csharp"] public static string FormatSummary(string summary){
string header = "ScottOnWriting: ";

//Remove the leading "ScottOnWriting: " if (summary.StartsWith(header)){
return summary.Substring(header.Length);
} return summary;
}

public static string FormatPubDate(DateTimeOffset pubDate)
{ return pubDate.ToString("h:mm, MMM d");
} [/sourcecode]

View

Now that the groundwork has been laid, we can write our actual HTML view.  First we need to add our javascript function:

[sourcecode language="html"] <asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server"> <script type="text/javascript"> $(document).ready(function () { startTicker('#tweets', 2, 4500);
}); </script> </asp:Content> [/sourcecode]

This javascript function will do nothing unless ticker.js exists in your scripts folder. It will end up in the page header and will be executed as soon as the document has finished rendering. Also note that we are passing 2 in here. We could pass in any number we wanted. Scott explains more about this in his article.

Now, the fact is that the original implementation using a ListView basically iterated over all the objects in the datasource and output a select piece of HTML for each item in that collection. So, we’ll do the same.

[sourcecode language="html"] <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

<h2>Dynamic News Ticker Demo</h2> <p> This demo shows a ticker whose contents are populated dynamically. This particular example pulls the most recent tweets from
<a href="http://twitter.com/ScottOnWriting">my Twitter account</a> and displays them in a ticker, showing two entries at a time. </p> <h3>@ScottOnWriting's Latest Tweets</h3> <div class="ticker twoRows medium"> <ul id="tweets"> <%foreach (var item in this.Model) {  %> <li> <div class="header" style="font-weight: normal"> <%= item.Title.ToString()%> </div> <div class="footer">Tweeted @ <%: item.Date.ToString()%></div> </li> <%} %> </ul> </div> </asp:Content>

[/sourcecode]

Note the careful placement of our Foreach  statement. Our list item (<li/>) and the HTML with in it will be repeated on each pass over the loop body. Also, note how we are using var item in this.Model. Our View knows exactly what datatype has been passed to it. In fact, our view is actually View<Model.Model>. Yes, its a generic. And we are using var here to avoid typing Model.Model over and over again.

 

So, in a nutshell, the above code does the exact same thing as a ListView Control.

Hit run and it should be working.