[英]How to render a newsfeed in an asp.net mvc4 partial view
我有一個新的MVC4項目。
在_Layout.cshtml中,我具有以下內容:
<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像普通視圖一樣放置即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.