在我最近的一个项目中,我使用 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;
}
等等等等
然后您只需像这样在视图中调用它
<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 扩展都是您的朋友! :-)
HTH
查尔斯