asp.net-mvc – 用于局部视图的ASP.NET MVC 3控制器操作

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 用于局部视图的ASP.NET MVC 3控制器操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是MVC的新手,我不明白如何正确使用部分视图.我正在尝试在我的MVC应用程序中显示来自博客站点RSS源.我正在使用Razor,我有以下结构:
Controllers/HomeController.cs
Controllers/RSSController.cs

Views/Home/Index.cshtml

Shared/_Layout.cshtml
Shared/_RSS.cshtml

HomeController的:

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的局部视图.

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