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>
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()
);
}
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.