The ASP.NET MVC project template comes with Bootstrap scaffolding by default. And Bootstrap comes with default styling for active navbar links. So you might find it a little odd that the ASP.NET bootstrap template does not style the active menu item by default.
It can, it just seems as if this functionality wasn’t included out of the box:
If you plan on utilizing the bootstrap’s powerful navigational layout, you should definitely add styling for the current page. It helps users keep track of where they are within the application and assists with navigation.
To do so, we can add the active
class dynamically on the shared layout by checking the current routing data. Here’s how:
Markup
When you create a new ASP.NET Web Application using MVC, the project should already contain some default pages and navigational links in the navbar. The navbar is defined as part of the shared layout in the Views folder. Your Solution Explorer should look like this:
In the _layout.vbhtml
file, you should find the following markup:
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
In order to highlight the current tab in the Bootstrap Navbar, the <li>
element needs to be given the class named active
. As an example, just try hard coding it in on any one of the current links:
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
This should look like the screenshot from above. But what we’d really like to do, is generate the active class dynamically for each li
depending on the current page. We’ll insert the string active
with an extension method called IsActive
that will take in parameters for the Controller and Route.
We can use our extension method to insert the active class on the appropriate action link like this:
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class='@Html.IsActive("Home", "Index")'>
@Html.ActionLink("Home", "Index", "Home")
</li>
<li class='@Html.IsActive("Home", "About")'>
@Html.ActionLink("About", "About", "Home")
</li>
<li class='@Html.IsActive("Home", "Contact")'>
@Html.ActionLink("Contact", "Contact", "Home")
</li>
</ul>
</div>
Extension Method
If you don’t already have one, create a folder in your project named Utilities and add a static class
(or Module
in VB) named Utilities or Extensions.
Then, we’ll add an extension method called IsActive
ontop of the HtmlHelper
class. We’ll use this to return the active
class if the passed in controller text and action text match the current route.
To programmatically determine the current controller and action, we’ll use the ViewContext
property on our HtmlHelper object. The ViewContext exposes, among other things, a property containing the RouteData
which contains a collection of URL parameter values and default values for the route
in its Values
property.
The whole thing should look like this:
public static class Utilities
{
public static string IsActive(this HtmlHelper html,
string control,
string action)
{
var routeData = html.ViewContext.RouteData;
var routeAction = (string)routeData.Values["action"];
var routeControl = (string)routeData.Values["controller"];
// both must match
var returnActive = control == routeControl &&
action == routeAction;
return returnActive ? "active" : "";
}
}
Finally, in order for your view to access this method, you’ll have to make sure you import the namespace into your view using the razor syntax like this:
@using YourProjectName.Utilities
Run your project and the current page should be highlighted!
Closing Remarks
You’ll notice that the login pages do not highlight when you navigate to the default account pages provided. See if you can use the info here to modify the _loginPartial
page in the Shared Layout section. If you get stuck, you can look at the full demo below.
Chris Way has a great blog post on Setting the active link in a Twitter Bootstrap Navbar in ASP.NET MVC. He comes up with a single method to generate the <li>
element and the <a>
element nested inside of it since there is largely redundant routing info. I’ve opted away from that for maximal flexibility as it locks you into a single method for producing links, but it does provide a terser inline syntax if that’s all you need to do.
Also, a lot of the basis for this code was taken from the StackOverflow question How to add active
class to Html.ActionLink
in ASP.NET MVC
Source Code:
You can view the full working solution on GitHub in both VB and C#
https://github.com/KyleMit/CodingEverything/tree/master/MVCBootstrapNavbar
Permalink to article - Published with markdown via stackedit.io
Very nice solution, well written article. Thanks a lot!
ReplyDeleteMachine Learning Projects for Final Year machine learning projects for final year
DeleteDeep Learning Projects assist final year students with improving your applied Deep Learning skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include Deep Learning projects for final year into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Deep Learning Projects for Final Year even arrange a more significant compensation.
Python Training in Chennai Python Training in Chennai Angular Training
great one.... thank you very much.. :)
ReplyDeleteHi. It took me awhile to find a good solution for this issue... Well, this one is well explained and it works like a charm. Thanks :)
ReplyDeletehow to download source code there is not any link
ReplyDeleteYou can just plug this into any existing MVC project, no need for any source code.
DeleteGreat..... Thanks
ReplyDeleteperfect (y)
ReplyDeleteGreat solution!
ReplyDeleteThank you! Finally a solution!
ReplyDeleteIn ASP.NET 5, there is no longer HtmlHelper, and instead of @Html.ActionLink, it is "a asp-controller="Home" asp-action="Index"". Any idea how to get the active menu highlighted?
ReplyDeleteReplace the HtmlHelper with IHtmlHelper to get it working in ASP.NET 5 MVC 6 RC1
DeleteGreat step by step solution, thanks for the help!
ReplyDeleteGreat example Kyle - Thank You!
ReplyDeleteTo get this to worik with ASP.NET 5, MVC 6, replace the HtmlHelper with IHtmlHelper. Presumably this is needed because of the way dependency injection is used. I got the idea to try this after skimming Startup.cs Listing 2 code in this article in Visual Studio Magazine ASP.NET MVC 6 and Tag Helpers, Part 2.
Very Good ! Thanks you friend
ReplyDeletetwitter bootstrap horizontal dropdown menu active in mvc 4 razor master page
ReplyDeleteExcellent! Thank you!
ReplyDeleteVery good senior! #Salute
ReplyDeleteGrate job! Thanks
ReplyDeleteis working for singal menu how to apply for dropdown menu
ReplyDeletemultilevel dropdown menu
ReplyDeleteplease can you help me
ReplyDeletewoow.. cool. its perfectly working, after spending couple of day on google.
ReplyDeleteThanks a lot.
How do you get this working with areas
ReplyDeleteThanks for sharing!
ReplyDeleteHelps me, thanks for sharing!
ReplyDeleteThis solution worked for me as well. I did make a small change to fit my needs though. I had one navbar item for each controller, irrespective of the actions.
ReplyDeleteThe modified code is given below, in case it helps somebody.
//commented below
//var returnActive = control == routeControl &&
// action == routeAction;
//added new code
var returnActive = control == routeControl;
if (!String.IsNullOrEmpty(action))
{
returnActive = (returnActive && action == routeAction);
}
In my layout file:
li class="@Html.IsActive("MyController","")"
thanks a lot
ReplyDeleteThis weblog seems to get a great deal of site visitors. How do you promote it? It gives a nice individual twist on things. I guess getting something useful or substantial to post about is the most important factor. ipad psd
ReplyDeleteI was following your blog regularly and this one is very interesting and knowledge attaining. Great effort ahead. you can also reach us for website development in chennai website design company in chennai
ReplyDeleteI was following your blog regularly and this one is very interesting and knowledge attaining. Great effort ahead. you can also reach us for Digital Marketing
ReplyDeleteEasyWay Logistics.!!
ReplyDeleteLooking for a Customs clearance Service, Truck service, Freight forwarder, Shipping a Cargo, Import & Export ..??
Freight Forwarding Agencies For Sea
Cargo Agents For Sea International
Freight Forwarding Agencies For Air
C&F Agents For Import
Domestic and Coastal Container Service
ODC Transportation in India
Thanks for sharing good content
ReplyDeleteweb designer skills
Stupendous blog huge applause to the blogger and hoping you to come up with such an extraordinary content in future. Surely, this post will inspire many aspirants who are very keen in gaining the knowledge. Expecting many more contents with lot more curiosity further.
ReplyDeleteDigital Marketing Course in Raipur
Wonderful blog found to be very impressive to come across such an awesome blog. I should really appreciate the blogger for the efforts they have put in to develop such an amazing content for all the curious readers who are very keen of being updated across every corner. Ultimately, this is an awesome experience for the readers. Anyways, thanks a lot and keep sharing the content in future too.
ReplyDeleteDigital Marketing training
Course material is consistently open on the web and they are nonconcurrent, so there's no compelling reason to plan uncommon excursions to a library by the same token. The entirety of this makes internet learning alluring. education
ReplyDeleterastgele görüntülü konuşma - kredi hesaplama - instagram video indir - instagram takipçi satın al - instagram takipçi satın al - tiktok takipçi satın al - instagram takipçi satın al - instagram beğeni satın al - instagram takipçi satın al - instagram takipçi satın al - instagram takipçi satın al - instagram takipçi satın al - binance güvenilir mi - binance güvenilir mi - binance güvenilir mi - binance güvenilir mi - instagram beğeni satın al - instagram beğeni satın al - polen filtresi - google haritalara yer ekleme - btcturk güvenilir mi - binance hesap açma - kuşadası kiralık villa - tiktok izlenme satın al - instagram takipçi satın al - sms onay - paribu sahibi - binance sahibi - btcturk sahibi - paribu ne zaman kuruldu - binance ne zaman kuruldu - btcturk ne zaman kuruldu - youtube izlenme satın al - torrent oyun - google haritalara yer ekleme - altyapısız internet - bedava internet - no deposit bonus forex - erkek spor ayakkabı - webturkey.net - karfiltre.com - tiktok jeton hilesi - tiktok beğeni satın al - microsoft word indir - misli indir
ReplyDeleteI see a website so good. It can download and zoom photos on Instagram.
Deletehttps://instazoom.mobi/
DeleteMy energetic arranging made them graduate secondary school and going to the college. There was no doubt in my psyche that advanced education was a "unquestionable requirement," and I wasn't going to begin my profession without it. https://www.pips.com.sg/open-house
ReplyDeleteaşk kitapları
ReplyDeleteyoutube abone satın al
cami avizesi
cami avizeleri
avize cami
no deposit bonus forex 2021
takipçi satın al
takipçi satın al
takipçi satın al
takipcialdim.com/tiktok-takipci-satin-al/
instagram beğeni satın al
instagram beğeni satın al
btcturk
tiktok izlenme satın al
sms onay
youtube izlenme satın al
no deposit bonus forex 2021
tiktok jeton hilesi
tiktok beğeni satın al
binance
takipçi satın al
uc satın al
sms onay
sms onay
tiktok takipçi satın al
tiktok beğeni satın al
twitter takipçi satın al
trend topic satın al
youtube abone satın al
instagram beğeni satın al
tiktok beğeni satın al
twitter takipçi satın al
trend topic satın al
youtube abone satın al
takipcialdim.com/instagram-begeni-satin-al/
perde modelleri
instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
instagram takipçi satın al
betboo
marsbahis
sultanbet
takipçi satın al
ReplyDeleteinstagram takipçi satın al
https://www.takipcikenti.com
toptan iç giyim tercih etmenizin sebebi kaliteyi ucuza satın alabilmektir. Ürünler yine orjinaldir ve size sorun yaşatmaz. Yine de bilinen tekstil markalarını tercih etmelisiniz.
ReplyDeleteDigitürk başvuru güncel adresine hoşgeldiniz. Hemen başvuru yaparsanız anında kurulum yapmaktayız.
tutku iç giyim Türkiye'nin önde gelen iç giyim markalarından birisi olmasının yanı sıra en çok satan markalardan birisidir. Ürünleri hem çok kalitelidir hem de pamuk kullanımı daha fazladır.
nbb sütyen hem kaliteli hem de uygun fiyatlı sütyenler üretmektedir. Sütyene ek olarak sütyen takımı ve jartiyer gibi ürünleri de mevcuttur. Özellikle Avrupa ve Orta Doğu'da çokça tercih edilmektedir.
yeni inci sütyen kaliteyi ucuz olarak sizlere ulaştırmaktadır. Çok çeşitli sütyen varyantları mevcuttur. iç giyime damga vuran markalardan biridir ve genellikle Avrupa'da ismi sıklıkla duyulur.
iç giyim ürünlerine her zaman dikkat etmemiz gerekmektedir. Üretimde kullanılan malzemelerin kullanım oranları, kumaşın esnekliği, çekmezlik testi gibi birçok unsuru aynı anda değerlendirerek seçim yapmalıyız.
iç giyim bayanların erkeklere göre daha dikkatli oldukları bir alandır. Erkeklere göre daha özenli ve daha seçici davranırlar. Biliyorlar ki iç giyimde kullandıkları şeyler kafalarındaki ve ruhlarındaki özellikleri dışa vururlar.
marsbahis
ReplyDeletebetboo
sultanbet
marsbahis
betboo
sultanbet
I am highly grateful to you for sharing useful information with the users
ReplyDeletethis is amazing site thanks for sharing
Bootstrap Studio
I am definitely enjoying your blog and looking forward to new updates... Getting a Turkish e visa from Turkey was one of the most difficult tasks for travelers but now you can get an online e visa Turkey fast processing service.
ReplyDeleteExtraordinary blog went amazed with the content that they have developed in a very descriptive manner. This type of content surely ensures the participants to explore themselves. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.
ReplyDeleteData Science Training
Stupendous blog huge applause to the blogger and hoping you to come up with such an extraordinary content in future. Surely, this post will inspire many aspirants who are very keen in gaining the knowledge. Expecting many more contents with lot more curiosity further.
ReplyDeleteData Science Certification in Bhilai
Ucuz, kaliteli ve organik sosyal medya hizmetleri satın almak için Ravje Medyayı tercih edebilir ve sosyal medya hesaplarını hızla büyütebilirsin. Ravje Medya ile sosyal medya hesaplarını organik ve gerçek kişiler ile geliştirebilir, kişisel ya da ticari hesapların için Ravje Medyayı tercih edebilirsin. Ravje Medya internet sitesine giriş yapmak için hemen tıkla: ravje.com
ReplyDeleteİnstagram takipçi satın almak için Ravje Medya hizmetlerini tercih edebilir, güvenilir ve gerçek takipçilere Ravje Medya ile ulaşabilirsin. İnstagram takipçi satın almak artık Ravje Medya ile oldukça güvenilir. Hemen instagram takipçi satın almak için Ravje Medyanın ilgili sayfasını ziyaret et: instagram takipçi satın al
Tiktok takipçi satın al istiyorsan tercihini Ravje Medya yap! Ravje Medya uzman kadrosu ve profesyonel ekibi ile sizlere Tiktok takipçi satın alma hizmetide sunmaktadır. Tiktok takipçi satın almak için hemen tıkla: tiktok takipçi satın al
İnstagram beğeni satın almak için Ravje medya instagram beğeni satın al sayfasına giriş yap, hızlı ve kaliteli instagram beğeni satın al: instagram beğeni satın al
Youtube izlenme satın al sayfası ile hemen youtube izlenme satın al! Ravje medya kalitesi ile hemen youtube izlenme satın almak için tıklayın: youtube izlenme satın al
Twitter takipçi satın almak istiyorsan Ravje medya twitter takipçi satın al sayfasına tıkla, Ravje medya güvencesi ile organik twitter takipçi satın al: twitter takipçi satın al
Thankyou for giving me useful information.
ReplyDeletePlease keep posting. 메이저사이트
Yes i am totally agreed with this article and i just want to say that this article is very nice and vey informative. More blogs please.
ReplyDelete경마사이트
경마
This blog iswhat im exactly looking for. Great! and Thanks to you. 카지노사이트
ReplyDeleteWhat an interesting article! I'm glad i finally found what i was looking for. 토토
ReplyDeleteaşk kitapları
ReplyDeleteyoutube abone satın al
cami avizesi
cami avizeleri
avize cami
no deposit bonus forex 2021
takipçi satın al
takipçi satın al
takipçi satın al
takipcialdim.com/tiktok-takipci-satin-al/
instagram beğeni satın al
instagram beğeni satın al
btcturk
tiktok izlenme satın al
sms onay
youtube izlenme satın al
no deposit bonus forex 2021
tiktok jeton hilesi
tiktok beğeni satın al
binance
takipçi satın al
uc satın al
sms onay
sms onay
tiktok takipçi satın al
tiktok beğeni satın al
twitter takipçi satın al
trend topic satın al
youtube abone satın al
instagram beğeni satın al
tiktok beğeni satın al
twitter takipçi satın al
trend topic satın al
youtube abone satın al
takipcialdim.com/instagram-begeni-satin-al/
perde modelleri
instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
instagram takipçi satın al
You can make a video how to do it. If you want to publish your video on tiktok use this site https://soclikes.com/buy-tiktok-followers to get more followers
ReplyDeleteHmm , very interesting thoughts! I think In order for more interested people to read your thoughts, you should post it on Instagram, and use the services of buy instagram likes to quickly increase their amount.
ReplyDeleteLoved the way you wrote it, thanks for sharing such great information. If you want to get info about Kenya evisa application, you can read out the Kenya evisa portal, you can fill out the Kenya evisa application form in minutes, and then you will pay the kenya e visa fees to enter kenya legally.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThere are a few things you really wanted to consider before you begin saving and this incorporates the school the kid will join in, the course they will be seeking after and the charges for something similar. 토토사이트
ReplyDeletekids coding class curriculum I would like to say that this blog really convinced me to do it! Thanks, very good post.
ReplyDeleteThanks for sharing great information. Keep sharing such useful information... Who wish to travel in India can easily apply for an Indian visa. India has now reopened tourism. India visa for Australian citizens, 30 Days Tourist E-Visa (30 Days E-Tourist Visa ETA validity is 120 days from the date of grant) has been reinstated with immediate effect
ReplyDeleteThanks for sharing excellent information. Keep sharing such useful information.. e Visa India can be easily obtained through online india e visa website.
ReplyDeleteDifferent businesses will not consider applicants except if they have an adequate degree of execution in their school work. In this way, you can see that businesses regularly view at schooling as a sort of "demonstrating ground" for their forthcoming employees.coding for kids
ReplyDeleteThank you so much for this code..
ReplyDeleteI am very impressed with the way you write. Your blog is very informative. Thankyou for this important information. Ukraine tourist visa express application system is a modern way of applying for a visa which takes just 5 minutes to apply and within 30 minutes you can get your e visa on your Email.
ReplyDeleteAmong the wide decisions accessible, abroad instruction is one of the most worthwhile and advantageous decision.Best School in Electronic City
ReplyDeleteHii,
ReplyDeleteThis is Great Post!!
Thanks for sharing with us!! this is Really useful for me.. Please Keep here some updates.Website Development Company
Regard !!!
Exellent your post. i reaching daily on your blogs. thanks for sharing this informative information.
ReplyDeleteBuy YouTube Views
Buy YouTube Subscribers
Buy YouTube Live Stream Views
Buy Facebook Live Views
Buy Instagram Reels Views
Buy Instagram Live Views
Buy Instagram Followers
Buy Facebook Views
Buy 500 YouTube Views
Wow.. Very informative article thanks for sharing please keep it up.. After submitting the application and paying the fee for Indian visa, you can get a visa in a few days. India e visa cost depends on your visa type.
ReplyDeletetiktok jeton hilesi
ReplyDeletetiktok jeton hilesi
referans kimliği nedir
gate güvenilir mi
tiktok jeton hilesi
paribu
btcturk
bitcoin nasıl alınır
yurtdışı kargo
Thanks for sharing such a useful post.
ReplyDeleteWeb Development Services in Chennai
Android Application Development Services in Chennai
What a great explanation in yours posts.. International travelers who wish to travel to Azerbaijan for tourism and business purpose need to apply for azerbaijan electronic visa through e visa application.
ReplyDeleteWe’re a Web Design Bali with over a decade of experience in building user friendly, secure websites that help strengthen your business.
ReplyDeleteAn investment property is a property that has been purchased for the sole purpose of generating income. Investment properties in Bali Investment properties in Bali can produce a return on investment in the form of rental returns or capital growth. Capital growth occurs when the value of the property has increased over time.
ReplyDeleteYou will find us operating from wherever is necessary to manage your money securely and effectively. We have wealth management singapore offices in Singapore to provide local market knowledge, impartial advice and personal service excellence.
ReplyDeleteOur vegan menu crafted by Indian food in Bali specialists and top-rated chefs, is the first of its kind on Seminyak We feel that everyone in Bali should have the opportunity to experience the difference Queens Indian Cuisine brings to the table, whether you are on Seminyak - Kuta - Nusa Dua - Ubud – the best Indian food in Bali is here. We are Bali's best-kept secret in the search for amazing Indian food.
ReplyDeleteAt Yoga Bali we offer unique Yoga Teacher Training in Bali and online and have graduated over 50 successful yoga teacher trainees from all corners of the globe. Our 80 video Yoga Teacher Training Course is internationally accredited. Our 80 Hour Yoga Online Video Training is designed to connect existing teachers with a robust body of further knowledge and professional up-skilling with our dedicated teaching team.
ReplyDeleteDunia Ide Bisnis sendiri membutuhkan kreativitas, karena jika tidak maka akan kalah oleh banyaknya pesaing di luar sana. Kamu harus membuat sebuah bisnis yang penuh dengan inovasi dan bukan hanya sekedar melakukan promosi saja. Kamu juga harus memberikan pelayanan terbaik agar nantinya produk dan juga usahamu disukai oleh masyarakat.
ReplyDeleteGood Finance Blog and advisors are compared to life coaches because they can help with many complex financial decisions throughout your life. They deal with other financial professionals daily and typically know if you’re paying too much for something or not getting a competitive rate.
ReplyDeleteIn this day, it seems like everyone is advertising themselves as a digital marketing agency. But how do you know which one to choose?
ReplyDeleteIt would help if you considered many things when selecting the best digital marketing agency for your brand or company.
The following article will provide 5 tips on finding the top best digital marketing agency to help you make an informed decision and ensure for your business ideas goals!
This is a great site too. Lots of great stuff and reporting! Keep it up! You can apply online & get your Turkish e visa in just a few clicks if you fill out the Turkish visa application form via the Turkey evisa website.
ReplyDeleteI love this post. Best from Medium.com and site123.me
ReplyDeleteİnstagram takipçi satın al! İnstagram takipçi sitesi ile takipçi satın al sende sosyal medyada fenomen olmaya bir adım at. Sende hemen instagram takipçi satın almak istiyorsan tıkla:
ReplyDelete1- takipçi satın al
2- takipçi satın al
3- takipçi satın al
Hii,
ReplyDeleteThis is Great Post.. for me, Thanks for sharing with us!!
Buy Real Facebook Live Stream Views
Buy Facebook Comments
Buy Facebook Video Views
What do you get every time you go grocery shopping?ThingsyoudoforbeautyWhat's an ideal Christmas/holiday for you?INDIA'S BEST OFF SITE SEO PROVIDER CHEAPEST AND FASTEST OFF SITE SEO SERVICE IN INDIA infocompanion educatijhn
ReplyDeleteExcellent post. Please keep posting such information. This site is amazing. Do you know how much does an Indian e visa cost? Indian e Visa cost depends on your nationality and your visa type. You can find out more about the Indian Visa on our website.
ReplyDeleteHii,
ReplyDeleteThanks for sharing with us. i hope you will updtes your blos on reguarlly bassis
Ethical Hacking
Cybersecurity Course
Penetration Testing Course
The Intect
Web Application VAPT
Thick Client VAPT