ASP.NET MVC - 基于控制器的样式列表项 [英] ASP.NET MVC - style list item based on controller
问题描述
我的最终目标是有一个菜单,添加一个类到列表项与我当前的页面相关联。
My ultimate goal is to have a menu that adds a class to the list item that associates with the current page I am on.
所以我设置了使得每个控制器将与我的菜单中的项目相关联。我需要添加一个类到该列表项(改变颜色,背景,任何)。
So I have it set up such that each controller will be associated with an item in my menu. I need to add a class to that list item (changing the color, background, whatever).
有简单的方法吗?传递一个值到View,然后什么?
Is there a simple way to do this? Pass a value to the View, then what?
推荐答案
在我最近的一个项目中,我使用HtmlHelper扩展,来自ViewContext.RouteData.Values集合。
In a recent project of mine I did it using HtmlHelper extensions and getting data from the ViewContext.RouteData.Values collection.
因此建立一个简单的扩展,例如:
So building off a simple extension like this:
public static string OnClass(this HtmlHelper html, bool isOn)
{
if (isOn)
return " class=\"on\"";
return string.Empty;
}
您可以建立任意数量的组合,例如
You can build up any number of combinations, e.g.
只是测试当前操作:
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;
}
Etc等。
那么你只需在你的视图中调用它。
Then you simply call it in your view(s) like so
<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扩展是你的朋友! : - )
Which ever way you look at it, HtmlHelper extensions are your friend! :-)
HTHs
Charles
HTHs
Charles
这篇关于ASP.NET MVC - 基于控制器的样式列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!