How to set class=”current” on active page in master page in ASP.Net

One problem which I faced in using master page with template(s) was, setting the class=”current” for the currently active page. As every problem has a solution, I too found one.

You have to make certain changes in Master Page and add few line of code in .cs page. I’ll telling you the way which I used plus I’ll be attaching the file with the this post (for your ease) so that you can download and see how it works.

Download Demo Work


In your master page make following changes in the menu section (i.e MasterPage.master)

<div id="aps_menu">   <ul>   <li><a href="home.aspx" id="homelink" runat="server" class="home">Home</a></li>   <li><a href="about.aspx" id="aboutlink" runat="server" class="about">About</a></li>   <li><a href="contact.aspx" id="contactlink" runat="server" class="contact">Contact</a></li>               </ul>   </div>



And In you code window of master page (i.e MasterPage.master.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SetCurrentPage();
    }

    private void SetCurrentPage()
    {
        var pagename =Convert.ToString( GetPageName());
        switch (pagename)
        {
            case "home.aspx":
                homelink.Attributes["class"] = "current";
                break;
            case "about.aspx":
                aboutlink.Attributes["class"] = "current";
                break;
            case "contact.aspx":
                contactlink.Attributes["class"] = "current";
                break;
        }
    }

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


JavaScript, ASP.Net & PHP Web Developer. Connect with me on Facebook and Twitter.

Share This Post

Related Articles

Powered by Paras Babbar · Designed by Paras Babbar