0

I'm trying to target the ID of an anchor within a user control named myMenu. The user control is on a master page. So, I'm trying to add a class of "active" from one of the content pages so it will highlight the link for that particular page. Right now I have:

if (Master != null)
        {
            var sitenav = (UserControl)Master.FindControl(id: "myMenu");
            if (sitenav != null)
            {
                var navlink = sitenav.Parent;

            }
        }

I'm still trying to figure out the logic here and can't find anything that has that info. I know I'd do the htmlanchor as the type?

html in user control:

<li><a runat="server" ID="linka" href="#">Link A</a></li>
<li><a runat="server" ID="linkb" href="#">Link B</a></li>
<li><a runat="server" ID="linkc" href="#">Link C</a></li>
<li><a runat="server" ID="linkd" href="#">Link D</a></li>
PaulR
  • 23
  • 1
  • 7

1 Answers1

0

MasterPage.cs:

... class MasterClass ...

public void performAction(bool toggle){
  if (toggle){
    myId.class += "active"; //something like that
  }
}

ContentPage.cs

(MasterClass)performAction(true);

This is how you can access a master page function and get it to do something on the master page elements.

To add a css class from code behind, I'd refer you to this answer which is both elegant and complete. Caspar Kleijne's answer


So your complete solution would be:

From within the Page you can cast the Master page to a specific type (the type of your own Master that exposes the desired functionality), using as to side step any exceptions on type mismatches:

Content Page:

var master = Master as MyMasterPage;
if (master != null)
{
    master.AddClass("active");
}

In the above code, if Master is not of type MyMasterPage then master will be null and no method call will be attempted; otherwise it will be called as expected.

MasterPage

public void AddClass(string classname ){
// add a class
myMenu.CssClass = String.Join(" ", myMenu
           .CssClass
           .Split(' ')
           .Except(new string[]{"",classname})
           .Concat(new string[]{classname})
           .ToArray()
   );
}
Community
  • 1
  • 1
Himanshu
  • 490
  • 1
  • 8
  • 17
  • I can't seem to get that to work? Is there a way in the content page code behind to have something like: linka.Attributes("class") == "active"; using the FindControl method to target the link ID within the user control? – PaulR Jun 07 '16 at 20:21