我是MVC的新手,我不了解如何正确使用局部视图。我正在尝试在MVC应用程序中显示来自博客站点的RSS feed。我正在使用Razor,并且具有以下结构:

Controllers/HomeController.cs
Controllers/RssController.cs

Views/Home/Index.cshtml

Shared/_Layout.cshtml
Shared/_Rss.cshtml


家庭控制器:

 namespace MvcApp.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                ViewBag.Message = "Welcome to ASP.NET MVC!";

                return View();

            }

        }
    }


RssController:

namespace MvcApp.Controllers
{
    public class RSSFeedController : Controller
    {

        public ActionResult RssFeed()
        {
            string strFeed = "http://foo.wordpress.com/category/foo/feed/";

            using (XmlReader reader = XmlReader.Create(strFeed))
            {
                SyndicationFeed rssData = SyndicationFeed.Load(reader);

                return View(rssData);
            }
        }

    }
}


_Rss.cshtml:

@using System.ServiceModel.Syndication;
@using System.Text;
@using System.Xml.Linq;

<h2>RSSFeed</h2>
@foreach (var item in ViewData.Model.Items)
{
string URL = item.Links[0].Uri.OriginalString;
string Title = item.Title.Text;
StringBuilder sb = new StringBuilder();
foreach (SyndicationElementExtension extension in item.ElementExtensions)
{
    XElement ele = extension.GetObject<XElement>();
    if (ele.Name.LocalName == "encoded" && ele.Name.Namespace.ToString().Contains("content"))
    {
        sb.Append(ele.Value + "<br/>");
    }
}
Response.Write(string.Format("<p><a href=\"{0}\"><b>{1}</b></a>", URL, Title));
Response.Write("<br/>" + sb + "</p>");
}


_Layout.cshtml:

<div id="main">
    @RenderBody()
</div>
<div id="BlogContent">
    @Html.Partial("_Rss");
</div>


我的困惑是如何调用控制器动作来获取局部视图?

最佳答案

您需要调用PartialView而不是View,这是经过修改的操作的外观:

    public ActionResult RssFeed()
    {
        string strFeed = "http://foo.wordpress.com/category/foo/feed/";

        using (XmlReader reader = XmlReader.Create(strFeed))
        {
            SyndicationFeed rssData = SyndicationFeed.Load(reader);

            return PartialView(rssData);
        }
    }


然后,您将需要一个名为RssFeed的局部视图。

09-25 16:27