asp.net-mvc – 在MVC ASP.NET中使用/显示RSS源的简单方法

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 在MVC ASP.NET中使用/显示RSS源的简单方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是MVC框架的新手,并且想知道如何将RSS数据从控制器传递给视图.我知道需要转换成一个IEnumerable列表.我看到一些创建一个匿名类型的例子,但是无法弄清楚如何将RSS源转换为通用列表并将其传递给视图.

我不希望它是强类型的,因为将有多个调用各种RSS源.

有什么建议么.

解决方法

我一直在玩一个在MVC中做WebParts的方式,基本上是UserControls包装在一个webPart容器中.我的一个测试UserControls是一个RSS Feed控件.我使用Futures dll中的RenderAction HtmlHelper扩展来显示它,所以控制器动作被调用.我使用SyndicationFeed类来做大部分的工作 @H_301_10@using (XmlReader reader = XmlReader.Create(Feed)) { SyndicationFeed RSSData = SyndicationFeed.Load(reader); return View(RSSData); }

下面是控制器和UserControl代码

控制器代码是:

@H_301_10@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; } } }

UserControl

@H_301_10@<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Index.ascx.cs" Inherits="MvcWidgets.Views.RSSWidget.Index" %> <div class="RSSFeedTitle"><%= Html.Encode(ViewData.Model.Title.Text) %> &nbsp; <%= 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>

后面的代码修改为有一个类型的模型

@H_301_10@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> { } }
原文链接:https://www.f2er.com/aspnet/246495.html

猜你在找的asp.Net相关文章