我的最终目标是拥有一个菜单,它会向与我当前所在页面相关联的列表项添加一个类。
因此,我已经设置好每个控制器将与我的菜单中的一个项目相关联。 我需要向该列表项添加一个类(更改颜色,背景等)。
是否有一种简单的方法来实现这一点?传递一个值到视图,然后呢?
因此,我已经设置好每个控制器将与我的菜单中的一个项目相关联。 我需要向该列表项添加一个类(更改颜色,背景等)。
是否有一种简单的方法来实现这一点?传递一个值到视图,然后呢?
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;
}
等等等等。
然后你只需要在你的视图中这样调用它
<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 Charles