ASP.NET C# With list navigation how to set id="current" on active navigation page?

asp.net, c#

Solution

You should look into setting the `class` of your menu items rather than the `id` in order to display it as highlighted.

You can do something as so. Add an `id` and `runat="server"` to each of your links:

<li><a href="home.aspx" id="HomeLink" runat="server"><i class="home"></i> Home</a></li>
<li><a href="Calendar.aspx" id="CalendarLink" runat="server"><i class="calendar"></i>Calendar</a></li>
<li><a href="Bill.aspx" id="BillLink" runat="server"><i class="list"></i>Bills</a></li>

Then in the code-behind of your master page, you can set the classes to each as they're navigated to:

protected void Page_Load(object sender, EventArgs e)
{
    SetCurrentPage();
}

private void SetCurrentPage()
{
    var pageName = GetPageName();

    switch (pageName)
    {
        case "home.aspx":
            HomeLink.Attributes["class"] = "current";
            break;
        case "Calendar.aspx":
            CalendarLink.Attributes["class"] = "current";
            break;
        case "Bill.aspx":
            BillLink.Attributes["class"] = "current";
            break;
    }
}

private string GetPageName()
{
    return Request.Url.ToString().Split('/').Last();
}

This will set the class of link that matches your current page to `current`. Of course you will need to define that class in your style sheet. But this should work.

Problem

I'm still learning asp.net and wanted to know if there was a simple way to set the id="current" to the navigation bar so that depending on the page a user was on it would highlight that page. My template is set up to use the id="current" to change the style of the link and I have i class to set the style of each tab. Here is the code in my Site.Master ``` <nav id="navigation" class="style-1"> <div class="left-corner"></div> <div class="right-corner"></div> <ul class="menu" id="responsive"> <li><a href="home.aspx" id="current"><i class="home"></i> Home</a></li> <li><a href="Calendar.aspx"><i class="calendar"></i>Calendar</a></li> <li><a href="Bill.aspx"><i class="list"></i>Bills</a></li> </ul> </nav> ``` Like I said, I'm still learning so i'm not sure if it would be better to place it in a ContentPlaceHolder. I tried to just request the URL and do if statements but I wasn't sure how to set the id=. Any help would be great. Thanks

Original source