我更深入地研究了 MVC 和 Umbraco,并创建了一个使用自定义控制器的解决方案。基本方法是这样的。
在项目的 Models 文件夹中创建一个模型
namespace MyProject.Models
{
public class MenuModel
{
// My Model contains just a set of IPublishedContent items, but it can
// contain anything you like
public IEnumerable<IPublishedContent> Items { get; set; }
}
}
在 Views > Shared 文件夹中创建一个新的局部视图
@inherits UmbracoViewPage
@{
Layout = null;
}
<ul>
@* Iterate over the items and print a link for each one *@
@foreach (var page in Model.Items)
{
<li><a href="@page.Url()">@page.Name</a></li>
}
</ul>
创建一个 SurfaceController 来执行一些业务逻辑,例如获取节点和构建模型
using System.Web.Mvc;
using MyProject.Models;
using Umbraco.Core;
using Umbraco.Web;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;
namespace MyProject.Controllers
{
public class NavMenuController : SurfaceController
{
public ActionResult Render(RenderModel some)
{
// Get the current homepage we're under (my site has multiple, because it is multi-language)
var currentHomePage = CurrentPage.AncestorOrSelf(1);
// Create model object
var menuModel = new MenuModel();
// Select descendant "Artikel" nodes of the current homepage and set them on the menu model
menuModel.Items = currentHomePage.Descendants("Artikel").Where(x => x.IsVisible());
// Return the partial view called NavMenu
// Do any processing you like here...
return PartialView("NavMenu", menuModel);
}
}
}
使用这行代码从任何地方调用新的局部视图:
@Html.Action("Render", "NavMenu")
我还在 our.umbraco.org 上发布了这个:
http://our.umbraco.org/forum/developers/api-questions/45339-Umraco-6-Looking-for-the-MVC-equivalent-of-codebehind-file?p=0#comment163126