Twitter bootstrap + asp.net masterpages, how to set navbar item as active when user selects it?

折月煮酒 提交于 2019-11-30 02:04:32

We solved it with the following function at Master Page:

 <script type="text/javascript">
        $(document).ready(function () {
            var url = window.location.pathname;
            var substr = url.split('/');
            var urlaspx = substr[substr.length-1];
            $('.nav').find('.active').removeClass('active');
            $('.nav li a').each(function () {
                if (this.href.indexOf(urlaspx) >= 0) {
                    $(this).parent().addClass('active');
                }
            });
        });
    </script>

Here is what I have used in Razor:

<li class="@(Model.PageName == "DataEntryForms" ? "active" : "")">
  <a href="DataEntryForms">     
    Data Entry Forms
  </a>
</li>
<li class="@(Model.PageName == "UserAdmin" ? "active" : "")">
  <a href="UserAdmin">      
    User Administration
  </a>
</li>

Just define the name of the page as property in the model, then complete the test for each li that you have.

 <script type="text/javascript">
     $(document).ready(function () {
         var url = window.location;
         $('ul.nav li a').each(function () {
             if (this.href == url) {
                 $("ul.nav li").each(function () {
                     if ($(this).hasClass("active")) {
                         $(this).removeClass("active");
                     }
                 });
                 $(this).parent().parent().parent().addClass('active');
                 $(this).parent().addClass('active');                     
             }
         });
     });
</script>

Assuming that the active class is set correctly by ASP.net, I would recommend an easier solution:

// Add the class to the parent li element of the active a element:
$('#NavigationMenu ul li a.active').parent().addClass('active');

// Remove the active class from the a element:
$('#NavigationMenu ul li a.active').removeClass('active');

Using ASP.net routing, this solution works smoothly in my current project.

And if you want to manipulate the active item of the menu, I would recommend to use the MenuItemDataBound of the menu control in code behind instead. But in my case, this was not necessary.

Megrez7

Solution by "sujit kinage" worked best for me, however I had to change one line:

var url = window.location.origin + window.location.pathname;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!