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.
To call a partial view from another partial view, we follow the same approach as we follow when we call partial view from the content page. Let's take an example. This is the code of 1st partial view. Notice that in above partial view, we are calling another partial view named "_View2" that is created below.
To create a partial view, right click on the Shared folder -> click Add -> click View.. to open the Add View popup, as shown below. You can create a partial view in any View folder. However, it is recommended to create all your partial views in the Shared folder so that they can be used in multiple views.
In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.
Partials often have an underscore prefix in their name. Other than that, nothing really separates them from other views.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With