问题描述
我开发了一个新闻页面在ASP.NET MVC和它的URL为本地主机/新闻网站。
为此,我公司开发的控制器,型号,以及遍历模型中的所有项目和一个视图显示它们。
此页面显示数据库中可用递减日期顺序排列的所有新闻。
我用路由新闻/ {ID}在细节显示特定的消息。
I have developed a news page for a website in ASP.NET MVC and its URL being localhost/News.For this purpose I have developed a controller, model, and a view that iterates over all items in a model and displays them.This page displays all the News available in database in descending order of date.I have used routing News/{id} for displaying that particular news in details.
我应该怎么做,如果我想显示说我主页上只剩下最后5新闻帖子?
可在控制器重复使用?或者,我需要重写code从我的数据库中获取新闻的记录?
What should I do, if I want to display say only last 5 news posts on my home page?Can the controller be reused? Or I'll need to rewrite the code for fetching news records from my database?
推荐答案
我最近有pretty很多同样的问题。我已经结束了使用MVC期货实行的RenderAction。一个很好的例子,说明如何使用它是在这里:
I recently had pretty much the same question. I've ended up using MVC Futures RenderAction implementation. A good example explaining how to use it is here:
基本上,你必须在你的ArticleController这样的事情(我不叫我的NewsController只是因为我疑神疑鬼假设新闻报的类型是新的集合:P)...
Basically you'd have something like this in your ArticleController (I don't call mine "NewsController" simply because I'm paranoid about it assuming "News" is a collection of type "New" :P)...
public ActionResult SidebarBox()
{
// I use a repository pattern to get records, just replace it with whatever you use
// also replace *.Take(5)* with however many you want returned
return View(repoArticles.GetAllArticles().Take(5).ToList());
}
和您的母版页(或任何你想要显示它),你会使用:
and in your Master Page (or wherever you want to display it) you'd use:
<% Html.RenderAction<ArticleController>(c => c.SidebarBox()); %>
然后与刚刚code你的边栏视图。
Then have a view with just the code for your sidebar box.
这篇关于在ASP.NET MVC新闻栏目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!