How to set navbar item as active when user selects it?

后端 未结 9 1284
耶瑟儿~
耶瑟儿~ 2021-02-05 18:45

I am a new ASP.NET Web Forms developer and trying to use Twitter Bootstrap with the Master Page. I am struggling with setting navbar item as active when user selects it. I creat

9条回答
  •  野性不改
    2021-02-05 19:10

    For those as myself that prefer server-side implementations, transform your li tags of interest to runat="server" on the Master.Page file. The code in question will look something similar to this:

     
    

    Then in the code behind of the Master page - Site.Master.vb or Site.Master.cs, depending on the language used - add the following in the Page Load event:

    VB.Net implementation:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Dim thisURL As String = Request.Url.Segments(Request.Url.Segments.Count - 1)
    
        Select Case thisURL
            Case "Default", "default.aspx"  
                tabContact.Attributes.Remove("active")
                tabHome.Attributes.Add("class", "active")
            Case "Contact"
                tabHome.Attributes.Remove("active")
                tabContact.Attributes.Add("class", "active")
        End Select
    End Sub
    

    C# implementation:

    Protected void Page_Load(Object sender, EventArgs e)
      {
        string thisURL = Request.Url.Segments[Request.Url.Segments.Length - 1];
    
        switch (thisURL)
        {
            Case "Default":
            Case "default.aspx": 
                {
                    tabContact.Attributes.Remove("active");
                    tabHome.Attributes.Add("class", "active");
                    break;
                }
    
            Case "Contact" : 
                {
                    tabHome.Attributes.Remove("active");
                    tabContact.Attributes.Add("class", "active");
                    break;
                }
        }
    }
    

    Since is "Default.aspx" the page that is supposed to be opened initially, the "Home" menu item will be highlighted as soon the user enters the website. An example is displayed below:

    For the sake of simplicity, only two navbar items were used in the example, but the same logic could be implemented if more are required.

    I hope can be of help.

提交回复
热议问题