简体   繁体   中英

How to dynamically add CSS to a menu on click in C#

I would like to dynamically add styling to my menu without using 15 different if-else statements. Perhaps a for loop?

`

C#

String activepage = HttpContext.Current.Request.Url.AbsolutePath;

          if (activepage.Contains("Cops"))
            {
                activateCOPS.Attributes.Add("class", "nav-link active");
            }
            else if (activepage.Contains("Opac"))
            {
                activateOPAC.Attributes.Add("class", "nav-link active");
            }
            else if (activepage.Contains("Etp-Tps"))
            {
                activateETP_TPS.Attributes.Add("class", "nav-link active");
            }
            else if (activepage.Contains("Eta"))
            {
                activateETA.Attributes.Add("class", "nav-link active");
            }... etc.

HTML:

<li class="nav-item">
  <a id="activateCOPS" class="nav-link" runat="server" href="Cops.aspx">COPS</a>
</li>
<li class="nav-item">
  <a id="activateOPAC" class="nav-link" runat="server" href="Opac.aspx">OPAC</a>
</li>

`

Thanks in advance!

You could do the following:

var themes = new Dictionary<string, Func<string[], bool>
{
     {"Employee", SetEmployeeSiteTheme },
     {"Government", SetGovermentSiteTheme} 
}

 if(themes.ContainsKey("Employee"))
     themes[key].Invoke("Some markup?");

Then inside those methods you can find your control, you can modify the markup, you are not generating a thousand if statements and you can expand the functionality later on depending on your needs.

This would be a better structure to control multiple layouts in my mind, this is how I might tackle your problem. Obviously I did not create a viable solution, I only demonstrated an approach to be a viable solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM