gpt4 book ai didi

css - 如何直观地指示 ASP.NET MVC 中的当前页面?

转载 作者:技术小花猫 更新时间:2023-10-29 10:17:29 25 4
gpt4 key购买 nike

作为讨论的基础。创建一个标准的 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>

如何设置指示当前页面的视觉 CSS 样式。例如,当在“关于”页面/ Controller 中时,我基本上想这样做:

<%= Html.ActionLink("About", "About", "Home", new {class="current"})%></li>

当然,在主页上时:

<%= Html.ActionLink("Home", "Index", "Home", new {class="current"})%></li>

(有一个 CSS 样式名称 current 在菜单中直观地指示这是当前页面。)

我可以将菜单 div 从母版页拆分为内容占位符,但这意味着我必须将菜单放在每个页面上。

任何想法,是否有一个很好的解决方案?

最佳答案

最简单的方法是从 ViewContext 的 RouteData 中获取当前 Controller 和操作。请注意签名的更改和使用 @ 转义关键字。

<% 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" : "" ) %>

请注意,您可以将它与 @Jon 的 HtmlHelper 扩展结合起来,并使其更简洁。

<%= Html.MenuLink( "About", "About", "Home", null, null, "current" ) %>

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 );
}
}

关于css - 如何直观地指示 ASP.NET MVC 中的当前页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1471362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com