Mag*_*son 17 css asp.net-mvc hyperlink selected
作为讨论的基础.创建一个标准的ASP.NET MVC Web项目.
它将在母版页中包含两个菜单项:
<div id="menucontainer">
<ul id="menu">
<li>
<%= Html.ActionLink("Home", "Index", "Home")%></li>
<li>
<%= Html.ActionLink("About", "About", "Home")%></li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
如何设置指示当前页面的可视CSS样式.例如,在About页面/控制器中,我基本上想要这样做:
<%= Html.ActionLink("About", "About", "Home", new {class="current"})%></li>
Run Code Online (Sandbox Code Playgroud)
当然,当在主页上时:
<%= Html.ActionLink("Home", "Index", "Home", new {class="current"})%></li>
Run Code Online (Sandbox Code Playgroud)
(CSS样式名称当前在菜单中可视地指示这是当前页面.)
我可以将菜单div从主页面分成内容占位符,但这意味着我必须将菜单放在每个页面上.
任何想法,有一个很好的解决方案吗?
tva*_*son 24
最简单的方法是从ViewContext的RouteData获取当前控制器和操作.请注意签名的更改和使用@来转义关键字.
<% var controller = ViewContext.RouteData.Values["controller"] as string ?? "Home";
var action = ViewContext.RouteData.Values["action"] as string ?? "Index";
var page = (controller + ":" + action).ToLower();
%>
<%= Html.ActionLink( "About", "About", "Home", null,
new { @class = page == "home:about" ? "current" : "" ) %>
<%= Html.ActionLink( "Home", "Index", "Home", null,
new { @class = page == "home:index" ? "current" : "" ) %>
Run Code Online (Sandbox Code Playgroud)
请注意,您可以将这个HtmlHelper扩展名与@ Jon's结合使用,并使其更清晰.
<%= Html.MenuLink( "About", "About", "Home", null, null, "current" ) %>
Run Code Online (Sandbox Code Playgroud)
MenuActionLink的位置
public static class MenuHelperExtensions
{
public static string MenuLink( this HtmlHelper helper,
string text,
string action,
string controller,
object routeValues,
object htmlAttributes,
string currentClass )
{
RouteValueDictionary attributes = new RouteValueDictionary( htmlAttributes );
string currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home";
string currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index";
string page = string.Format( "{0}:{1}", currentController, currentAction ).ToLower();
string thisPage = string.Format( "{0}:{1}", controller, action ).ToLower();
attributes["class"] = (page == thisPage) ? currentClass : "";
return helper.ActionLink( text, action, controller, new RouteValueDictionary( routeValues ), attributes );
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6641 次 |
| 最近记录: |