Enhance Your ASP.NET Website with Dynamic Link Styles

Having some trouble with my main menu on my ASP.NET website. I'm looking to have the selected link change its color to black and stay that way until a different link is clicked.

In simpler terms, I want the selected link to be highlighted.

I've managed to make it work using JavaScript, but the issue is that the style doesn't persist after a page reload (or at least it seems so).

This is my current JavaScript:

<script type="text/javascript">
    var last = "none";
    function LinkSelector(link) {
        if (last != "none") {
            document.getElementById(last).className = "NormalLink";
        }
        document.getElementById(link).className = "ActiveLink";
        last = link;
    }
</script>

While this script changes the class name when clicked, it doesn't maintain that state upon loading a new page.

Does anyone have a workaround for this? :)

Thank you in advance,

Sincerely,

Bo

Answer №1

My go-to choice for creating menus is the ASP:Menu control. It offers a great level of control over menu items.

One useful method that I often include in my masterpage is one that runs during the initial page load. This method goes through all the menu items in the control and selects the item corresponding to the current URL.

protected void Page_Load(object sender, EventArgs e) {
        if (!Page.IsPostBack) {
            SelectMenuItem();
        }
    }

private void SelectMenuItem() {
        string rawurl = Request.RawUrl.ToLower();

        rawurl = rawurl.Substring(rawurl.LastIndexOf("/") + 1);
        if (rawurl.IndexOf("?") >= 0)
           rawurl = rawurl.Substring(0, rawurl.IndexOf("?"));

        foreach (MenuItem mi in mnuMain.Items) {
            if (mi.ChildItems.Count == 0) {
                if (mi.Value == rawurl) {
                    mi.Selected = true;
                    break;
                }
            } else {
                foreach (MenuItem cmi in mi.ChildItems) {
                    if (cmi.Value == rawurl) {
                        mi.Selected = true;
                        break;
                    }
                }
                if (mi.Selected)
                    break;
            }
        }
    }

Here are some examples of menu items I use in my ASP menu control. Take note that I utilize the Value attribute to help identify which menu item corresponds to the requested URL in the method above.

<Items>
  <asp:MenuItem Text="Forms" Value="authorization">
    <asp:MenuItem Text="New Authorization Form" Value="createauthform.aspx" NavigateUrl="~/CreateAuthForm.aspx"></asp:MenuItem>
    <asp:MenuItem Text="Manage My Authorization Forms" Value="myrequests.aspx" NavigateUrl="~/MyRequests.aspx"></asp:MenuItem>
    <asp:MenuItem Text="Audit Attendance Form" Value="auditform.aspx" NavigateUrl="~/AuditForm.aspx"></asp:MenuItem>
    <asp:MenuItem Text="Tax Determination Statement" Value="taxstatement.aspx"  NavigateUrl="~/TaxStatement.aspx"></asp:MenuItem>
  </asp:MenuItem>
</Items>

Answer №2

One way to maintain the value of your "last" variable between function calls is by making it a static member of your function. You can learn how to do this by following this guide. This approach ensures that the value stays intact even when the function is called multiple times. It's worth experimenting to see if the value persists after page reloads.

If this method doesn't work for retaining the value, you may need to find a way to instruct ASP to store and recall the variable. As for providing guidance on that front, I'm afraid I won't be of much help.

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

Creating a sidebar that extends to the bottom of the webpage using

My friend is currently designing his website, and he has encountered an issue with the sidebar. He wishes for the sidebar to extend all the way down to the bottom of the page rather than just the visible portion within the browser window. You can view the ...

Making alterations to the bootstrap.scss document

Looking to personalize Bootstrap 4 using Sass. My goal is to contain the imports within specific classes in order to target only certain parts of the website. For example: .page-one, .page-two { /* imports go here */ } Customizing it by altering the ...

Using jQuery to create a nested table

I have a table that I would like to customize so that when a user clicks on a row, only the child table under that specific row is visible while the child tables under other rows are hidden. How can I achieve this using jQuery? <table class="mainTabl ...

Is it possible to replicate an HTML table using JavaScript without including the headers?

Discover a JavaScript snippet in this stack overflow post that allows you to create a button for automatically selecting and copying a table to the clipboard. When pasting the data into an Excel template, my users prefer not to include the header informat ...

Incorporating WordPress post identifiers into an enduring collection

I am currently using Wordpress posts with multiple custom meta fields to showcase various items. Users are able to search for items and add them to a collection or cart, similar to common e-commerce solutions found in WordPress. However, I am unsure of whe ...

Issues with Iframe { height:70%;} in Internet Explorer 8 and Firefox causing display problems

In my website's design, I have a div structure with an iframe to load pages. The header remains at the top seamlessly The footer stays at the bottom perfectly The content is positioned in the middle flawlessly However, the iframe does not stret ...

Learning to access a base64 encoded PDF file using JavaScript

var ajaxSettings = { url: urls.orders.list+"/"+singlePacket.requests[0].order_id+"/labels", //retrieve labels with ShipperAssigned status type: "GET", contentType: "application/json", headers: { "Authorizatio ...

Enhance User Experience with jQuery UI Droppable: Customize default elements from a saved list and expand drop zones for added functionality

Take a look at my current setup on JSFiddle: https://jsfiddle.net/w27g3xp2/1/ In the setup, there is an input box with some preset values. My objective is to generate and position 4 droppable elements based on the inputs in the field so that they appear i ...

When creating routes in Express 4.* using node.js, it is essential to use the root directory

Completely new to the world of node.js, I find myself navigating through an outdated and partially functioning course on udemy.com. In previous modules, I managed to successfully receive content through routes like app.get('/vegetables',functio ...

Issues with the proper functionality of the .ajax() method in Django

I'm currently facing an issue with my Ajax code while trying to interact with the database in order to edit model instances. I noticed that the first alert statement is functioning correctly, however, the subsequent alert statements are not working as ...

Having trouble with the Express.js app.post request functionality

I'm facing a challenge with the Express.js library. I've been attempting to set up a basic post request with the route. I have body-parser installed and am using it for the post data. If I specifically include app.post, it doesn't work, ...

Why is my JavaScript code functioning properly on jsfiddle but failing to work when run locally?

After recently creating JavaScript code that allows for form submission using the <form> tag, I encountered an issue when trying to implement it within an HTML page. Here is a snippet of the code: <script type="text/javascript"> var m ...

Is there a noticeable distinction or significant benefit between using auth.signOut() and signOut(auth)?

When it comes to logging out with Firebase, is there a significant difference or advantage between using auth.signOut() or signOut(auth)? This concept also applies to other authentication processes like logging in and signing up. The Firebase documentation ...

Attempting to bring in HTML through a helper, but Rails doesn't seem too thrilled about it

I have a form that triggers a remote GET request, leading to the display of a modal. The issue I'm facing is that multiple actions can utilize the same model, so I am attempting to employ a helper and jQuery to showcase different data based on what is ...

Monitor $localStorage for any modifications

Utilizing the ngStorage module, which can be accessed at this link: https://github.com/gsklee/ngStorage In order to maintain a lastSeenId for a real-time social feed in my hybrid app (Laravel/AngularJS), I am storing it in localStorage instead of $scope. ...

Steps for downloading a file attached to a gridview

It seems like I'm overlooking something quite straightforward. I am creating binary files that I am associating with a GridView. FileDownloadGrid.DataSource = downloadList; FileDownloadGrid.DataBind(); The part of the grid that interests me ...

It appears that my array is not being properly populated by my callback functions

I am encountering an issue with my callback functions. The objective of my code is to send 16 GET requests to a REST API in order to retrieve 16 distinct JSON files. These JSON files are then supposed to be converted into dictionaries representing the foot ...

Executing window.open from Html.Actionlink in ASP.NET MVC 4

Here is the code block I am working with: @foreach (System.Data.DataRow drEquipment in Model.EquipmentList.Rows) { <tr> <td valign="top">@drEquipment["ColumnName"]<br /></td> <td valign="to ...

What factors should be taken into account when running a process from an ASP.NET application directory?

My ASP.NET Web role involves running an audio effects utility on sound files that are generated when a specific Controller method is called. I am well-versed in using the Process object to execute a process, set the working directory, wait for exit, and ch ...

What could be causing the error message to appear stating that each list item must have a unique key when utilizing react-bootstrap in Nextjs?

My file currently contains keys for each child component, but it is still raising an error internally. I am unsure if I can resolve these issues on my own. export default function SecondaryNav(props:NavItems) { const router = us ...