这是关于ASP.NET MVC中的最佳实践的问题
我在MVC中创建了一个网站.因为每个页面都有一个菜单,我想我会创建一个基本控制器类,项目中的所有MVC控制器都继承该类.在基本控制器类的Initialize()函数中,我将加载我的菜单.通过这种方式,我可以保留我在一个地方加载菜单的逻辑并让它自动执行.
代码(C#):
public abstract class BaseController : System.Web.Mvc.Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
//Load the menu:
ViewBag.HeaderModel = LoadMenu();
}
}
public class HomeController : BaseController
{
public ActionResult Index()
{
//the menu is loaded by the base controller, so we can just return the view here
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
这就像一个魅力.现在这是问题所在.
在我看来,我在网站上列出了五篇最新文章.由于文章在网站上有自己的逻辑和自己的部分,我创建了一个ArticleController,它继承自BaseController,其动作显示了我最近的五篇文章的PartialResult.
public class ArticlesController : BaseController
{
public ActionResult DisplayLatestArticles()
{
var model = ... //abbreviated, this loads the latest articles
return PartialView("LatestArticles", model); …Run Code Online (Sandbox Code Playgroud)