Tuesday, June 16, 2015

Create a RSS reader in an Umbaco 7 MVC Partial View

There are several way to create and embed a RSS reader in an Umbraco page: using custom controllers, using XSL macros, etc...

But wath if we want to use a normal MVC Partial View without to develop a custom controller?

Well, it is really simple to achieve this goal with just a few C# lines.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@using System.ServiceModel
@using System.ServiceModel.Syndication
@using System.Xml
@{
 string url = "http://your_blog_rss_url";
 XmlReader reader = XmlReader.Create(url);
 SyndicationFeed feed = SyndicationFeed.Load(reader); 
 reader.Close(); 
}

@foreach(var feedItem in feed.Items)
{ 
 <div class="col-md-6">
  <article>
   <div class="date">
    <span class="day">@feedItem.PublishDate.Day</span>
    <span class="month">@GetMonthName(feedItems[i].PublishDate.Month)</span>
   </div>
   <h4 class="heading-primary"><a href="@feedItem.Links[4].Uri">@feedItems[i].Title.Text</a></h4>
   <p>@(feedItem.Summary.Text + "... ") <a href="@feedItem.Links[4].Uri" class="read-more">read more <i class="fa fa-angle-right"></i></a></p>
  </article>
 </div>
}

As you can see, only a couple odlines are required. At this point we just have to include this partial view in the page where we want to see our RSS feed.
Obviously, you can change the layout (the one here is what I used in my project).

Only 2 notes:
  1. I used "feedItem.Links[4].Uri" to retrieve the blog post url, this works if you use blogger. If you use other blogging platforms as sources, you'll have to check the Links collection to know "where" is the url you want.
  2. The "@GetMonthName" is just an Helper to convert the "number" of the month into its name.

No comments: