Determining the name of current view within a partial view in ASP.NET MVC
-
16-09-2019 - |
Question
I have a partial view in my test ASP.NET MVC application. This view is responsible to display application menu buttons.
I want to change the color of button which is currently active page. Currently I have written something like:
<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>
And set the view data in controller actions:
//in home action
ViewData["currentPage"] = "Home";
//in About action
ViewData["currentPage"] = "About";
This works but I have to modify every controller action. Is there any better method of automatically detecting the view and somehow change the partial view code to change the color accordingly.
Solution
I think you dont need ViewData["currentPage"]. Use ViewContext.RouteData.Values
instead:
Try this:
<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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow