Obtain the name of the current view in ASP.NET MVC 5 using Razor on the .cshtml side

As a student who is new to ASP.NET MVC and coming from ASP.NET Web Forms, I am accustomed to it.

Here is the list:

<ul class="sidebar bg-grayDark">
    <li class="active">
        <a href="@Url.Action("Index", "Home")">
            <span class="mif-home icon"></span>
            <span class="title">Home</span>
        </a>
    </li>
    <li class="bg-hover-black">
        <a href="@Url.Action("Index", "Product")">
            <span class="mif-shop icon"></span>
            <span class="title">Products</span>
            <span class="counter">14</span>
        </a>
    </li>
    <li class="bg-hover-black">
        <a href="@Url.Action("Index", "Category")">
            <span class="mif-flow-cascade icon"></span>
            <span class="title">Categories</span>
            <span class="counter">9</span>
        </a>
    </li>
    <li class="bg-hover-black">
        <a href="@Url.Action("Index", "User")">
            <span class="mif-users icon"></span>
            <span class="title">Users</span>
            <span class="counter">1</span>
        </a>
    </li>
</ul>

My objective: When a view is rendered, I want to add "active" to the that has been clicked on. For example, if I click on "Category", then the active class should be removed from Home and added to Category. The same applies for "bg-hover-black".

I initially attempted to achieve this using JavaScript:


    $(function () {
        $('.sidebar').on('click', 'li', function () {
            if (!$(this).hasClass('active')) {
                $('.sidebar li').removeClass('active');
                $(this).addClass('active');
            }
        })
    })
    

However, this approach did not work as expected because when the page loads, the HTML is re-rendered with "active" for the Home section. Removing "active" from Home would result in nothing being active onClick, except between clicks and page load.

Do you have any solutions? I have searched extensively online but haven't found anything helpful.

Apologies for any English errors, I am still learning :).

Thank you,

Hellcat8.

Answer №1

If you follow the convention of naming your page after the controller, you can easily retrieve the controller/page name using Razor:

@{
 var pageName = ViewContext.RouteData.Values["controller"].ToString();
}

<ul class="sidebar bg-grayDark">
    <li class="@(pageName == "Home" ? "active" : "")">
        <a href="@Url.Action("Index", "Home")">
            <span class="mif-home icon"></span>
            <span class="title">Home</span>
        </a>
    </li>
    <li class="bg-hover-black @(pageName == "Product" ? "active" : "")">
        <a href="@Url.Action("Index", "Product")">
            <span class="mif-shop icon"></span>
            <span class="title">Products</span>
            <span class="counter">14</span>
        </a>
    </li>
    <li class="bg-hover-black @(pageName == "Category" ? "active" : "")">
        <a href="@Url.Action("Index", "Category")">
            <span class="mif-flow-cascade icon"></span>
            <span class="title">Categories</span>
            <span class="counter">9</span>
        </a>
    </li>
    <li class="bg-hover-black @(pageName == "User" ? "active" : "")">
        <a href="@Url.Action("Index", "User")">
            <span class="mif-users icon"></span>
            <span class="title">Users</span>
            <span class="counter">1</span>
        </a>
    </li>
</ul>

This approach applies the active class on the server side and eliminates the need for client-side JavaScript.

Answer №2

Presented below is my innovative method for implementing a cascaded Bootstrap dropdown submenu, complete with the use of active classes within the _layout.cshtml file of a Razor Pages project.

The key components of this approach involve:

  • Retrieving the current page route by accessing
    ViewContext.RouteData.Values["page"]
    .
  • Opting for Anchor Tag Helpers over @Url.Action().

Implementation:

<ul class="nav navbar-nav">
    @{
        String pageRoute = ViewContext.RouteData.Values["page"].ToString();
    }
    <li class="dropdown @( pageRoute.Contains("/CustomerModel/") ? "active" : "" )">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Customer-Model <span class="caret"></span></a>
        <ul class="dropdown-menu">
            <li class="@( pageRoute.Contains("/Customers/") ? "active" : "" )"><a asp-page="/CustomerModel/Customers/Index">Customers</a></li>
            <li class="@( pageRoute.Contains("/Partners/")  ? "active" : "" )"><a asp-page="/CustomerModel/CustomerPermissions/Index">CustomerPermissions</a></li>
        </ul>
    </li>
    <li class="dropdown @( pageRoute.Contains("/StaffModel/") ? "active" : "" )">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Staff-Model <span class="caret"></span></a>
        <ul class="dropdown-menu">
            <li class="@( pageRoute.Contains("/Staff/")              ? "active" : "" )"><a asp-page="/StaffModel/Staff/Index">Staff</a></li>
            <li class="@( pageRoute.Contains("/StaffGroups/")        ? "active" : "" )"><a asp-page="/StaffModel/StaffGroups/Index">StaffGroups</a></li>
            <li class="@( pageRoute.Contains("/PermissionsGroups/")  ? "active" : "" )"><a asp-page="/StaffModel/PermissionsGroups/Index">PermissionsGroups</a></li>
            <li class="@( pageRoute.Contains("/AllowedModules/")     ? "active" : "" )"><a asp-page="/StaffModel/AllowedModules/Index">AllowedModules</a></li>
            <li class="@( pageRoute.Contains("/AllowedServices/")    ? "active" : "" )"><a asp-page="/StaffModel/AllowedServices/Index">AllowedServices</a></li>
        </ul>
    </li>
</ul>

Answer №3

If you want to retrieve the active action or controller's name, you can use the following code snippet:

var controllerName = ViewContext.RouteData.Values["controller"].ToString();
var actionName = ViewContext.RouteData.Values["action"].ToString();

After getting the names, you can apply a specific class to an li element based on the action name like this:

<li class="@(actionName == "HomePage" ? "active":"")"><a href="~/Account/HomePage">Home</a></li>

You can also combine both controller and action names for better specificity as shown below:

<li class="@(controllerName =="Account" && actionName == "HomePage" ? "active":"")"><a href="~/Account/HomePage">Home</a></li>

Answer №4

Just to clarify: Whenever the user clicks on an item, the page is altered.

As a result, your javascript code will execute, but then the entire page gets refreshed, bringing you back to the initial state (with Home being active as stated in the markup).

If you want to verify the current page, you can utilize location.href and compare it with the href URL, like so:

$(function() {
    $("ul.sidebar>li").removeClass("active");  // Alternatively, you could omit 'active' from the markup
    $("li>a[href=" + location.href + "]").closest("li").addClass("active");
});

Another approach, which might be more reliable, involves passing a token (such as a string, enum, or constant) within the view model for comparison purposes, for example:

<ul class='sidebar'>
    <li data-page='home'...
    ...
    <li data-page='categories'...

Then you can do something like this:

$(function() { 
    $("li[<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6a6f7a6f237e6f696b334e43616a6b62205e6f696b406f636b">[email protected]</a>]").addClass("active")

(or you could simply do it directly in the HTML markup...)

    <li data-page='categories' @(Model.PageName == 'Categories' ? "class=active" : "")>

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

Are you interested in becoming a part of the Mongo DB community?

Imagine a scenario where you have a hotel booking website and need to create an SQL database with 2 tables Booking booking Number Check-in Date Check-out Date Total Cost HotelID (foreign key) Hotel Hotel ID Name Location Other details If you we ...

Defeat the all-powerful !important tag and enable dialog customization for positioning

I am currently developing a browser extension and I am encountering an issue with using JQueryUI to display a modal dialog. The problem arises when certain websites, for example espn.com, also utilize JQueryUI but do not properly scope their own elements. ...

consistent height across the div when expanding

There is a recurring issue I encounter where it takes too long for me to solve the problem. My goal is to ensure that the bootstrap boxes at the bottom of the page have the same height. I attempted to set a fixed height in pixels using my CSS, but this cau ...

When the div element reaches the top of the page, it sticks to the top and is only displayed when the user

In the center of a full-screen hero section, there is a form. When it reaches the top, its position becomes fixed and additional classes are added through a script - such as shrinking its height and adding a background. What I aim to achieve is for the fo ...

What is the best method to display ID from a URL in a textbox or input field?

After creating a new employee, the system redirects to the edit page and passes along the employee ID, which contains different employee information. For instance, let's say I create one employee, it then redirects to the edit page with an employee I ...

Failure to trigger Bootstrap modal upon button activation

I am currently working on developing a basic student list webpage using bootstrap. My goal is to create a modal that pops up when the user clicks a button, allowing them to enter the required details. However, before implementing this feature, I decided to ...

Applying CSS to both pop-up and desktop interfaces can be achieved through the use of media queries or alternative solutions

I am facing a dilemma where I need to display the same content on both a pop-up and desktop view. While I have already implemented media queries to adjust the content for desktop and mobile views, I am struggling with displaying the same content on a pop ...

When the CSS grid is equipped with a sticky left column, it will horizontally scroll if the grid's width exceeds 100% of its containing element

I am facing an issue with a CSS grid layout that has sticky left and right columns as shown below: .grid { display: grid; grid-template-columns: repeat(10, 200px); } .grid > div { border: 1px solid black; background-color: white; } .sticky- ...

Tips for sending a large list as Ajax data in an MVC model

My morning was spent in vain as I attempted different "workarounds" that were suggested, usually for more specific scenarios than the one I am facing. My goal is to simply pass an ASP.NET MVC model using the JQuery load method. It seems promising when I us ...

Is it possible for my JQueryUI draggable items to smoothly transition into a different overflowing element?

On my iPad, I have two scrollable areas where I kept the overflow to auto, scroll, or hidden to allow scrolling. One section contains unenrolled students, and using JQueryUI with touchPunch, I can drag a student from the unenrolled bin into their appropria ...

Position a checkbox input and a <p> tag side by side on a single line

I've come across various solutions for this issue that involve using a label. Unfortunately, in this specific case, I am unable to utilize a label as it would cause complications. The current setup is as follows: <div className="terms-checkbox"> ...

Adjust the background color of Bootstrap 4 checkboxes

I'm trying to figure out how I can modify the background color of a Bootstrap 4 checkbox in this specific scenario. .custom-control-label::before, .custom-control-label::after { top: .8rem; width: 1.25rem; height: 1.25rem; } <link rel="style ...

The dropdown menu is extending beyond the bounds of the screen on mobile devices

When viewing my website on a mobile device, the select dropdown is going off the screen. I am using the bootstrap class form-control. Here is my code: <select name="service" formControlName="service" class="form-control shadow-none" style="width:100%"& ...

Setting up IdentityServer 4 with Internet Information Services (IIS)

I am currently working with IdentityServer 4 and using this link https://github.com/IdentityServer/IdentityServer4.Samples as a reference. However, I am facing an issue where IdentityServer loads and works fine when accessed through http://localhost:22530 ...

Tips for choosing an option from a react dropdown using Cypress

Exploring Cypress: I am currently working with the following code snippet. Although it seems to be functioning, I have a feeling that there might be a more efficient way to achieve the desired result. There are 25 similar dropdowns like this one on the pag ...

determining the directory for Internet Explorer driver logs

I've encountered an issue trying to set the IE Driver log path. I attempted to do this using Command-Line Code, see below: var optionsIe32 = new InternetExplorerOptions { IntroduceInstabilityByIgnoringProtectedMode ...

An issue arises with S3 Client's PutObjectRequest due to a WebException

Running into a problem with my PutObject on S3, I keep getting this WebException message: "A redirect was returned without a new location. This issue may be due to attempting to access buckets with periods in the name in a different region from what the c ...

Items that share identical height and margin values will appear with divergent visual presentations

I am trying to align three horizontal lines so that they are the same height and have an equal spacing between each other. However, due to variations in height and margins, some lines appear larger or smaller than others. How can I ensure they all have th ...

Guide on deploying Google App Script add-ons on Google Workspace Marketplace

Recently delving into Google App Script, I've taken my first steps in coding within the platform. Utilizing the deploy option provided by Google App Script, I successfully launched my app. However, upon deployment, I encountered difficulty locating my ...

The alignment of the horizontal menu items is off

Currently, I am working with asp.net and dealing with a horizontal menu issue. The alignment problem arises where the right side of Menu B appears higher than the left one (Menu A). I have included my code below for reference. Any suggestions or assistance ...