更好的选择是使用 _Layout.cshtml。_ViewStart 只是调用 _Layout.cshtml。
您可能不需要在此处查看部分视图。您可以使用呈现 PartialView 结果的子操作。
在你的
_Layout.cshtml:
你可以有
@{ Html.RenderAction("Navigation", "Home"); }
这指向 HomeController 和 Navigation Action
附加说明:Html.RenderAction 更好,因为它比 Html.Action 快得多。它可以有效地处理大量的 HTML,因为它将结果直接发送到响应。Html.Action 只返回一个带有结果的字符串。
Navigation Action 有它的 Navigation View,它几乎等同于您在视图中的内容。
主页/Navigation.cshtml:
@model IEnumerable<MvcApplication1.Controllers.NavViewModel>
@foreach (var nav in Model)
{
<li>@Html.ActionLink(nav.Title, nav.Url)</li>
}
HomeController.cs:
请注意,您可能将数据库访问作为依赖项注入以支持可测试性。
public class HomeController : Controller
{
private readonly ICakesRepository _cakesRepository;
//additional constructor to support testability.
public HomeController(ICakesRepository cakesRepository) {
_cakesRepository = cakesRepository;
}
//this can be removed if you the above with IOC/DI wire-up
public HomeController() {
_cakesRepository = new CakesRepository();
}
[ChildActionOnly]
[HttpGet]
public ActionResult Navigation() {
var articles = _cakesRepository.GetArticles();
var navBarList = articles.Select(nb => new NavViewModel { Title = nb.Title, Url = nb.Url });
return PartialView(navBarList);
}
}
附加支持类:
public class NavViewModel {
public string Title { get; set; }
public string Url { get; set; }
}
public interface ICakesRepository {
IEnumerable<Articles> GetArticles();
}
public class CakesRepository : ICakesRepository {
public IEnumerable<Articles> GetArticles() {
//call to a db
//fake db data
return new List<Articles>() {
new Articles(){Title = "Title1", Url = "http://urlone.com"},
new Articles(){Title = "Title2", Url = "http://urltwo.com"},
new Articles(){Title = "Title3", Url = "http://urlthree.com"}
};
}
}
public class Articles {
public string Title { get; set; }
public string Url { get; set; }
}