c# – 确定ASP.NET MVC中局部视图中当前视图的名称
作者:互联网
我在测试ASP.NET MVC应用程序中有部分视图.该视图负责显示应用程序菜单按钮.
我想更改当前活动页面的按钮颜色.目前我写了类似的东西:
<ul id="menu">
<% var activeClass = (string)(ViewData["currentPage"]) == "Home" ? "activeMenuButton" : ""; %>
<li><%= Html.ActionLink ("Home", "Index", "Home", new { @class = activeClass })%></li>
<% activeClass = (string)(ViewData["currentPage"]) == "About" ? "activeMenuButton" : ""; %>
<li><%= Html.ActionLink ("About", "About", "Home", new { @class = activeClass })%></li>
</ul>
并在控制器操作中设置视图数据:
//in home action
ViewData["currentPage"] = "Home";
//in About action
ViewData["currentPage"] = "About";
这有效但我必须修改每个控制器动作.有没有更好的方法来自动检测视图,并以某种方式更改部分视图代码以相应地更改颜色.
解决方法:
我认为你不需要ViewData [“currentPage”].改为使用ViewContext.RouteData.Values:
> SO – Getting the name of the controller and action method in the view in ASP.Net MVC
试试这个:
<ul id="menu">
<% var activeClass = (ViewContext.RouteData.Values["Controller"] == "Home"
&& ViewContext.RouteData.Values["Action"] == "Home") ? "activeMenuButton" : ""; %>
<li><%= Html.ActionLink ("Home", "Index", "Home", new { @class = activeClass })%></li>
<% activeClass = (ViewContext.RouteData.Values["Controller"] == "Home"
&& ViewContext.RouteData.Values["Action"] == "About") ? "activeMenuButton" : ""; %>
<li><%= Html.ActionLink ("About", "About", "Home", new { @class = activeClass })%></li>
</ul>
标签:c,css,asp-net-mvc,partial-views 来源: https://codeday.me/bug/20190527/1160465.html