0

I have the following menu:

<ul class="nav nav-tabs nav-stacked">
<li class="nav-header">Navigation Menu</li>
<li>@Html.MenuLink("Test Link", "Index", "Home", "active",true)</li>

MenuLink is a helper that sets a class to the ActionLink (href) element:

public static HtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string activeClass, bool checkAction)
        {
            string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
            string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

            if (string.Compare(controllerName, currentController, StringComparison.OrdinalIgnoreCase) == 0 && ((!checkAction) || string.Compare(actionName, currentAction, StringComparison.OrdinalIgnoreCase) == 0))
            {
                return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = activeClass });
            }

            return htmlHelper.ActionLink(linkText, actionName, controllerName);

        }

What I need is to set the class attribute to the parent HTML element, in this case the <li> element, so the final result would be:

<ul class="nav nav-tabs nav-stacked">
<li class="nav-header">Navigation Menu</li>
<li class="active"><href="....."></li>

instead of the actual result:

<ul class="nav nav-tabs nav-stacked">
<li class="nav-header">Navigation Menu</li>
<li><href="....."  class="active"></li>

Any clue, any advise is appreciated.

Thanks.

4

1 回答 1

0

代替 MenuLink 帮助器,您可以像这样简单地使用 @Url 帮助器:

<li class="active">
    <href="@Url.Action("Index", "Home")">
</li> 

并编写您的自定义 Helper 仅生成类名的结果(例如 active )

所以最终的代码看起来像这样:

<li class="@Html.YourCustomHelperForActiveTab("Index","Home")" >
    <href="@Url.Action("Index", "Home")">
</li> 

更新:对于某些人来说,为每个选项卡获取类的示例帮助器可能是这样的:(来源)

public static string ActiveTab(this HtmlHelper helper, string activeController, string[] activeActions, string cssClass)
{
    string currentAction = helper.ViewContext.Controller.
            ValueProvider.GetValue("action").RawValue.ToString();
    string currentController = helper.ViewContext.Controller.
            ValueProvider.GetValue("controller").RawValue.ToString();

    string cssClassToUse = currentController == activeController 
         && activeActions.Contains(currentAction)
                               ? cssClass
                               : string.Empty;
    return cssClassToUse;
}
于 2013-07-02T18:17:40.940 回答