February 13, 2015 07:23 by
Peter
Each time we are making application with some quite menu it's nice to own the essential practicality to focus on selected menu item in ASP.NET MVC 6 . There are some solutions you'll notice within the web, but when I've tried to use one it hasn't been operating excellent. So, let's produce our own in 3 steps.
1. First of all we want to make MVC HTML helper class, containing method to use the appropriate CSS class based on some conditions.
2. Now, we want the CSS class itself to be applied for selected menu item, it is very easy, background color change, font modification, etc.
3. The menu HTML ought to be changed to use our helper while rendering page.
And here is the example helper class code:
public static class MenuHelper
{
public static string IsSelected(this HtmlHelper html, string controller = null, string action = null)
{
const string cssClass = "selected";
string currentAction = (string)html.ViewContext.RouteData.Values["action"];
string currentController = (string)html.ViewContext.RouteData.Values["controller"];
if (String.IsNullOrEmpty(controller))
controller = currentController;
if (String.IsNullOrEmpty(action))
action = currentAction;
return controller.Split(';').Contains(currentController) && action.Split(';').Contains(currentAction) ?
cssClass : String.Empty;
}
}
Pretty easy, isn't it? we are setting the 'selected" CSS class based on the controller and action combination (both arguments are optional). sometimes we've in the menu only main pages, however we would like to tell user in a way regarding the context whereas he's opening sub-page. the best way is to stay the menu item highlighted when user is browsing some sub-pages. This helper implementation is supporting this case likewise. we are able to pass as arguments many controller names, or action names and for those groups we are able to highlight particular menu item.
Highlight menu item for Index action from Home controller:
class="@Html.IsSelected(null, "Index")"
Highlight menu item for several actions coming from one controller:
class="@Html.IsSelected(null, "Contact;About")"
HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.