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