MvcSiteMap generating a Menu without messing the breadcumbs

只谈情不闲聊 提交于 2019-11-27 05:23:21
NightOwl888

Make a template for the MenuHelperModel and give it a custom name, and put it in the /Views/Shared/DisplayTemplates/ folder. Then you can make a template for the SiteMapNodeModel and SiteMapNodeModelList and give them custom names. Copy the contents of MenuHelperModel.cshtml, SiteMapNodeModel.cshtml, and SiteMapNodeModelList.cshtml into your new custom helpers.

Then, change the overrides in each of the HTML helpers within the templates so they call the custom templates instead of the built-in templates.

// MyMenu.cshtml
@* // This template is for the root level *@
@model MvcSiteMapProvider.Web.Html.Models.MenuHelperModel
@using System.Web.Mvc.Html
@using MvcSiteMapProvider.Web.Html.Models

<ul id="menu">
    @foreach (var node in Model.Nodes) { 
        <li>@Html.DisplayFor(m => node, "MyMenuNode") @* <-- // Custom Node Helper Name *@
            @if (node.Children.Any()) {
                @Html.DisplayFor(m => node.Children, "MyMenuNodeList") @* <-- // Custom Node Helper Name *@
            }
        </li>
    }
</ul>


// MyMenuNodeList.cshtml
@* // This template is for the descendent lists below the root level *@
@model MvcSiteMapProvider.Web.Html.Models.SiteMapNodeModelList
@using System.Web.Mvc.Html
@using MvcSiteMapProvider.Web.Html.Models

<ul>
    @foreach (var node in Model) { 
        <li>@Html.DisplayFor(m => node, "MyMenuNode") @* <-- // Custom Node Helper Name *@
            @if (node.Children.Any()) {
                @Html.DisplayFor(m => node.Children, "MyMenuNodeList") @* <-- // Custom Node Helper Name *@
            }
        </li>
    }
</ul>



// MyMenuNode.cshtml
@* // This template is for the node *@
@model MvcSiteMapProvider.Web.Html.Models.SiteMapNodeModel
@using System.Web.Mvc.Html
@using MvcSiteMapProvider.Web.Html.Models

Testing @* <-- // If configured right, Testing will appear before every node *@

@if (Model.IsCurrentNode && Model.SourceMetadata["HtmlHelper"].ToString() != "MvcSiteMapProvider.Web.Html.MenuHelper")  { 
    <text>@Model.Title</text>
} else if (Model.IsClickable) { 
    if (string.IsNullOrEmpty(Model.Description))
    {
        <a href="@Model.Url">@Model.Title</a>
    }
    else
    {
        <a href="@Model.Url" title="@Model.Description">@Model.Title</a>
    }
} else { 
    <text>@Model.Title</text>
}

Then call your root template from the menu.

@Html.MvcSiteMap().Menu("MyMenu")

You can use this as a starting point, and then make the changes to the views accordingly to output your desired HTML.

Do note that the SiteMapNodeListHelper template ("MySiteMapNodeList" in this case) recursively calls itself for each successive level of nodes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!