8
我的最終目標是創建一個菜單,將類添加到與當前頁面相關聯的列表項中。基於控制器的ASP.NET MVC風格列表項目
因此,我設置了每個控制器都將與我的菜單中的項目相關聯。我需要向該列表項添加一個類(更改顏色,背景,等等)。
有沒有簡單的方法來做到這一點?傳遞一個值給View,然後呢?
我的最終目標是創建一個菜單,將類添加到與當前頁面相關聯的列表項中。基於控制器的ASP.NET MVC風格列表項目
因此,我設置了每個控制器都將與我的菜單中的項目相關聯。我需要向該列表項添加一個類(更改顏色,背景,等等)。
有沒有簡單的方法來做到這一點?傳遞一個值給View,然後呢?
在我最近的一個項目中,我使用HtmlHelper擴展並從ViewContext.RouteData.Values集合獲取數據。
所以建立過一個簡單的擴展是這樣的:
public static string OnClass(this HtmlHelper html, bool isOn)
{
if (isOn)
return " class=\"on\"";
return string.Empty;
}
您可以構建任何數量的組合,例如
只是測試當前的動作:
public static string OnClass(this HtmlHelper html, string action)
{
string currentAction = html.ViewContext.RouteData.Values["action"].ToString();
return html.OnClass(currentAction.ToLower() == action.ToLower());
}
測試了一系列行動:
public static string OnClass(this HtmlHelper html, string[] actions)
{
string currentAction = html.ViewContext.RouteData.Values["action"].ToString();
foreach (string action in actions)
{
if (currentAction.ToLower() == action.ToLower())
return html.OnClass(true);
}
return string.Empty;
}
測試行動和控制器:
public static string OnClass(this HtmlHelper html, string action, string controller)
{
string currentController = html.ViewContext.RouteData.Values["controller"].ToString();
if (currentController.ToLower() == controller.ToLower())
return html.OnClass(action);
return string.Empty;
}
等等,等等
然後你只需調用它在你的視圖(S),像這樣
<ul id="left-menu">
<!-- simple boolean -->
<li <%= Html.OnClass(something == somethingElse) %>>Blah</li>
<!-- action -->
<li <%= Html.OnClass("Index") %>>Blah</li>
<!-- any number of actions -->
<li <%= Html.OnClass(new string[] { "Index", "Details", "View" }) %>>Blah</li>
<!-- action and controller -->
<li <%= Html.OnClass("Index", "Home") %>>Blah</li>
</ul>
以往的方式,你看哪個吧,擴展的HtmlHelper是你的朋友! :-)
HTHS
查爾斯
相關:http://stackoverflow.com/questions/906423/jquery-add-class-on-current-item – 2009-08-05 02:37:00
@Robert - 類,但我想要一個非JavaScript解決方案。我會理想地認爲,因爲我擁有服務器上所需的所有信息,所以我可以在服務器上執行此操作。 – Martin 2009-08-05 12:17:51