如何在asp.net mvc4部分视图中呈现新闻提要
本文关键字:新闻 视图 asp net mvc4 | 更新日期: 2023-09-27 18:05:53
我有一个新的MVC4项目。
In my _Layout。我有以下内容:
<div class="container maincontent">
<div class="row">
<div class="span2 hidden-phone">
@*
In here is a RenderSection featured. This is declared in a section tag in Views'Home'Index.cshtml.
If this is static text for the whole site, don't render a section, just add it in.
You should also be able to use @Html.Partial("_LoginPartial") for example.
This _LoginPartial will need to be a cshtml in the Shared Views folder.
*@
@{ Html.RenderPartial("_NewsFeed"); }
</div>
<div class="span10">
@RenderBody()
</div>
</div>
</div>
我的部分视图是
<div class="row newsfeed">
NEWS FEED
@foreach (var item in ViewData["newsfeed"] as IEnumerable<NewsItem>)
{
<div class="span2 newsfeeditem">
<h3>@item.NewsTitle</h3>
<p>@item.NewsContent</p>
@Html.ActionLink("More", "NewsItem", "News", new {id=@item.Id}, null)
</div>
}
是否有一种方法可以让部分视图进行数据调用?目前,我必须在控制器中为每个动作执行以下操作:
ViewData["newsfeed"] = _db.NewsItems.OrderByDescending(u => u.DateAdded).Where(u => u.IsLive == true).Take(4);
return View(ViewData);
我已经把一个模型传递给一个视图,因为我不能再把这个传递给它。
我知道我做错了什么,只是不确定是什么或在哪里。
我只是想能够在我的_layout中进行渲染调用,然后局部视图知道收集数据,然后渲染自己。还是我理解错了?我想我是想使用它像一个ascx…
您应该从使用RenderPartial
切换到RenderAction
。这允许您再次通过管道并生成一个ActionResult,就像部分一样,但是使用服务器端代码。例如:
@Html.RenderAction("Index", "NewsFeed");
然后制定NewsFeedController
并提供Index
动作方法:
public class NewsFeedController : Controller
{
public ActionResult Index()
{
var modelData = _db.NewsItems.OrderByDescending(...);
// Hook up or initialize _db here however you normally are doing it
return PartialView(modelData);
}
}
然后,您只需在Views/NewsFeed/Index中拥有CSHTML,就像普通视图一样。cshtml位置。