What is the main focus of the active view in MVC2?

So, you can find my website at www.kristianbak.com.

I've created a CSS class named activebutton, but I want it to dynamically change when another view is active. Right now, it's statically coded in the HTML (sitemaster).

Does anyone have a clever solution for this?

Answer №1

If you want to test the current action and apply a CSS class if it matches, you can do so by using the following code:

<% if (ViewContext.RouteData.GetRequiredString("action") == "About") { %>
    ... highlight here
<% } %>

An even better approach would be to create an HTML helper to generate the menu automatically. Here is an example of how you could implement it:

public static MvcHtmlString MenuItem(
    this HtmlHelper htmlHelper, 
    string text,
    string action, 
    string controller
)
{
    var li = new TagBuilder("li");
    var routeData = htmlHelper.ViewContext.RouteData;
    var currentAction = routeData.GetRequiredString("action");
    var currentController = routeData.GetRequiredString("controller");
    if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
        string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
    {
        li.AddCssClass("active");
    }
    li.InnerHtml = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
    return MvcHtmlString.Create(li.ToString());
}

You can then use this helper in your code like so:

<ul>
    <%= Html.MenuItem("Home", "Home", "Home") %>
    <%= Html.MenuItem("About Me", "About", "Home") %>
    <%= Html.MenuItem("My Work", "Work", "Home") %>
    <%= Html.MenuItem("Blog", "Index", "Blog") %>
    ...
</ul>

This will automatically add the active class to the anchor if the current request matches the action and controller of the link.

Answer №2

After reading this post, I came up with a method of my own:

My method is similar but has one major flaw. Let's imagine we have 3 links: Home, About, and Contact.

We also have 4 controllers with default Index actions: HomeController, AboutController, ContactController, and BiographyController.

In the content of the About page, there is a link to the Biography page, which calls the Index action in the Biography controller.

However, when clicking on the biography link, I want the About page to remain selected as it belongs to the "About" section.

Most of the solutions I found online do not address this crucial issue.

The solution I devised does not require using sessions or adding messy code in Views. All we need are these lines of code:

 <%= Html.ActionMenuItem("Home", "Index", "Home") %>
 <%= Html.ActionMenuItem("About", "Index", "About") %>
 <%= Html.ActionMenuItem("Contact", "Index", "Contact") %>

Since the solution to this problem is quite detailed, I have shared it on my blog:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to understand the reason behind why the button is not being displayed

I'm having trouble with my quiz app. I have a button to submit answers and move on to the next question, but whenever I try to place it within the div that contains the quiz, the button disappears. Can someone please help me figure out what's wro ...

Bootstrap 4 Collapse - Ensuring that collapsed elements remain open when expanding other accordions

Can someone help me figure out how to keep an element open when another one is opened? Here is an example: https://getbootstrap.com/docs/4.0/components/collapse/ <div id="exampleAccordion" data-children=".item"> <div class="item"> & ...

Using jQuery, disregard elements that are not hidden

Currently, I am working with a jQuery validator and I am attempting to utilize the ignore: ':hidden:not feature for all controls that contain an ID with " selecting" in it. Here is my current code snippet: sb.AppendLine(@" ignore: ':hidden: ...

The hover CSS effect in the dropdown menu does not apply to sibling elements, but does work on descendant elements

Below are two sets of code for creating a dropdown menu. Although similar, the codes have a slight difference. In both cases, I have assigned classes to the main list item and submenu. The main heading has been given the 'heading' class with an a ...

The color of the ellipsis value does not match properly

In my table, I have lines that end with 3 dots '...' when the text overflows. To achieve this, I used the ellipsis value of the text-overflow property. While this works well and the '...' are displayed when resizing the window, I encoun ...

Adjustable div heights for text within inline elements

How can I make two inline-table divs (content and sidebar) have the same height regardless of their content? I've experimented with various attributes, but nothing seems to be working. You can view my website here. ...

Enhance a link using jQuery to allow it to expand and collapse

I am currently working on an MVC view that features a 3-column table showcasing a list of products. The first column, which contains the product names, is clickable and directs users to a specific product page. I am looking to implement functionality where ...

Struggling to locate the correct path for the CSS file in Express and Handlebars

As part of a student exercise, I am attempting to access an API containing information about presidents and style them using CSS. However, I am facing issues with linking the style.css file. I have tried various methods to change the path and public path ...

Animating back with a jQuery if statement

Is there a way to implement an if statement that triggers an animation when the right image reaches +400px, and then animates back to -400px upon hovering over the image? $('#left img').mouseenter(function() { $('#right img').animate ...

What steps should I take to prevent my <mat-card> from expanding whenever messages are shown in Angular 9?

I have a <mat-card> containing a login form on my page. However, when error messages are displayed, the vertical size of the <mat-card> changes and I need it to remain the same. Is there a way to prevent this from happening? Below, you will ...

In relation to CSS and HTML

I recently started working on a website built with HTML/CSS and encountered an issue with links highlighting when hovered over. The problem arises from the main image on the homepage containing an embedded link, causing the area under it to also highlight ...

"Incorporate countless Bootstrap 4 carousels into one webpage for an enhanced user

I'm experiencing difficulties with the new Bootstrap 4. Can anyone provide guidance on how to incorporate multiple Bootstrap carousels into a single page? I've researched several websites, but most only offer solutions for Bootstrap 3. Your assi ...

Troubleshooting problems with CSS borders and margins in the anchor element

Having a peculiar box-model issue here. My header is filled with links, but despite setting 0px margins, the links are displaying with 2px margins around each one. To demonstrate the problem, I've created a test page located at . Ideally, each link i ...

The CSS outline has a soft, rounded appearance rather than a sharp

https://i.sstatic.net/Mkb8Z.png Is there a way to prevent my outline from having rounded corners as it expands during the animation? Note: The issue seems to be present on Linux and MS Edge, but works fine on Mozilla Firefox. Any solutions for MS Edge us ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

The art of jQuery: Effortlessly animate the deletion of a CSS property

When using jQuery, I often "collapse" certain DOM elements by decreasing their width to 0px and fading them out. Here is an example: $(".slideoutmenu").animate({ width: 0, opacity: 0}, function() { $(this).hide(); }); The widths of these elements can var ...

Certain HTML elements on the webpage are not functioning properly when attempting to incorporate a div tag

One of the challenges I'm currently facing is that the links for HOME and ABOUT ME in the header section are not accessible when the 'data' div is added. Strangely, the DOWNLOAD and CONTACT ME links still work fine. This issue seems to be oc ...

Images of equal height without compromising the resolution

How can I create responsive images with the same height inside a DIV tag, with a specified height of 200px? Any assistance would be greatly appreciated. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="desc ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

Managing button spacing with Bootstrap 4 in an Angular 2 CLI application

I find it puzzling why the alignment between Bootstrap buttons within the Angular 2 CLI project is not working as expected. To address this issue, I followed the instructions to create a new Angular 2 CLI app outlined here: https://angular.io/guide/quicks ...