2013-07-02 30 views
0

我有以下菜單:asp.net MVC組父元素類

<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是設定一類到ActionLink的(HREF)元件的輔助:

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); 

     } 

我需要的是將class屬性設置爲父HTML元素,在這種情況下爲<li>元素,因此最終結果將爲:

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

而不是實際的結果:

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

任何線索,任何提醒理解。

謝謝。

+0

MvcSiteMap將使這更容易,並給你靈活的樣式菜單項和標題。 –

回答

0

相反,你可以簡單地使用@url助手這樣的MenuLink幫手:

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

,並編寫自定義助手只生成類名的結果(例如激活)

所以最終代碼會是這個樣子:

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

更新:它可能也有幫助,一些人提到一個例子幫手獲取類EA ch標籤可能是這樣的:(Source)

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; 
}