I would like to mark the current node and it's parent with a css class. I was searching around and found these links:
http://mvcsitemap.codeplex.com/discussions/257786 http://mvcsitemap.codeplex.com/discussions/245000
So I modified SiteMapNodeModelList.cshtml and now the current node is highlighted. But not sure how I should highlight the parent node.
<ul>
@foreach (var node in Model) {
<li class="@(node.IsCurrentNode ? "current" : "")" >@Html.DisplayFor(m => node)
@if (node.Children.Any()) {
@Html.DisplayFor(m => node.Children)
}
</li>
}
</ul>
To mark the parent node I've built an extension method that checks all immediate child elements (I only have 2 levels):
public static bool IsCurrentNodeOrChild(this SiteMapNodeModel node)
{
if (node.IsCurrentNode) return true;
return node.Children.Any(n => n.IsCurrentNode);
}
And changed MenuHelperModel.cshtml like this:
<ul id="menu">
@foreach (var node in Model.Nodes) {
<li class="@(node.IsCurrentNodeOrChild() ? "current" : "d")" >@Html.DisplayFor(m => node)
@if (node.Children.Any()) {
@Html.DisplayFor(m => node.Children)
}
</li>
}
</ul>
This now works perfectly. But is there really no simpler approach? Can't be the first man on earth that needs this?
That is really, cool, but when I keep creating extensions for this and that, I took a different approach but I should note that it is based on your idea :D
MainMenu.cshtml:
@model MvcSiteMapProvider.Web.Html.Models.MenuHelperModel
@using MvcSiteMapProvider.Web.Html.Models
@foreach (var node in Model.Nodes)
{
<li @((node.IsCurrentNode || node.Children.Any(n => n.IsCurrentNode)) ? "class=active" : "")>@Html.DisplayFor(m => node)</li>
}
and insert this into
_Layout.cshtml
@Html.MvcSiteMap().Menu("MainMenu")
Basically it does the same thing, just a little bit cleaner (in my opinion)
You may very well be the first person on Earth who needs this. Then again, I suspect that there are dozens of libraries of useful methods out there that could make MvcSiteMapProvider more useful.
MvcSiteMapProvider is an open source collaborative effort. If you spot something like this that could be useful to a great many people, we'd appreciate making a contribution by pull request @ GitHub on the dev branch. This idea would make a very nice contribution. I suggest adding the method to the SiteMapNodeModel object directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With