I've been playing around with a way of doing WebParts in MVC which are basically UserControls wrapped in a webPart container. One of my test UserControls is an Rss Feed control. I use the RenderAction HtmlHelper extension in the Futures dll to display it so a controller action is called. I use the SyndicationFeed class to do most of the work
using (XmlReader reader = XmlReader.Create(feed))
{
SyndicationFeed rssData = SyndicationFeed.Load(reader);
return View(rssData);
}
Below is the controller and UserControl code:
The Controller code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Xml;
using System.ServiceModel.Syndication;
using System.Security;
using System.IO;
namespace MvcWidgets.Controllers
{
public class RssWidgetController : Controller
{
public ActionResult Index(string feed)
{
string errorString = "";
try
{
if (String.IsNullOrEmpty(feed))
{
throw new ArgumentNullException("feed");
}
**using (XmlReader reader = XmlReader.Create(feed))
{
SyndicationFeed rssData = SyndicationFeed.Load(reader);
return View(rssData);
}**
}
catch (ArgumentNullException)
{
errorString = "No url for Rss feed specified.";
}
catch (SecurityException)
{
errorString = "You do not have permission to access the specified Rss feed.";
}
catch (FileNotFoundException)
{
errorString = "The Rss feed was not found.";
}
catch (UriFormatException)
{
errorString = "The Rss feed specified was not a valid URI.";
}
catch (Exception)
{
errorString = "An error occured accessing the RSS feed.";
}
var errorResult = new ContentResult();
errorResult.Content = errorString;
return errorResult;
}
}
}
The UserControl
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Index.ascx.cs" Inherits="MvcWidgets.Views.RssWidget.Index" %>
<div class="RssFeedTitle"><%= Html.Encode(ViewData.Model.Title.Text) %> <%= Html.Encode(ViewData.Model.LastUpdatedTime.ToString("MMM dd, yyyy hh:mm:ss") )%></div>
<div class='RssContent'>
<% foreach (var item in ViewData.Model.Items)
{
string url = item.Links[0].Uri.OriginalString;
%>
<p><a href='<%= url %>'><b> <%= item.Title.Text%></b></a>
<% if (item.Summary != null)
{%>
<br/> <%= item.Summary.Text %>
<% }
} %> </p>
</div>
with the code behind modified to have a typed Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ServiceModel.Syndication;
namespace MvcWidgets.Views.RssWidget
{
public partial class Index : System.Web.Mvc.ViewUserControl<SyndicationFeed>
{
}
}