1

我在 Umbraco 6.1.6 中创建了一个生成导航菜单的局部视图。

@inherits UmbracoTemplatePage
@using System.Collections;
@using System.Linq;
@{
   Layout = null;
   var articleParent = Model.Content.AncestorOrSelf(1);
}


<ul>
    @foreach (var page in articleParent.Descendants("Artikel").Where(x => x.IsVisible()))
{
   <li><a href="@page.NiceUrl()">@page.Name</a></li>
}

</ul>

我想在后端代码中获取此菜单项列表并在视图中呈现列表之前对其进行进一步处理。我该怎么做?我应该创建一个自定义控制器还是什么?我不想在视图代码中进行额外的处理。

谢谢

4

2 回答 2

2

我将创建一个扩展方法并将其放在 AppCode 文件夹中:

public static NodesExtensions
{
    public static void Process(this DynamicNodeList nodes)
    {
        foreach(var node in nodes)
        {
            //process node
        }
    }
}

而不是在你看来

@inherits UmbracoTemplatePage
@using System.Collections;
@using System.Linq;
@{
   Layout = null;
   var articles = Model.Content
                       .AncestorOrSelf(1)
                       .Descendants("Artikel");
   articles.Process();

   //you can now render the nodes 
}
于 2013-10-09T17:03:46.483 回答
0

我更深入地研究了 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

于 2013-10-10T15:29:49.007 回答