C# - How To Change Html Elements Attributes
Solution 1:
In order to access these controls from the server-side, you need to make them runat="server"
<ulid="nav"runat="server"><liclass="forcePadding"><imgsrc="css/site-style-images/menu_corner_right.jpg" /></li><liid="screenshots"><ahref="screenshots.aspx"title="Screenshots">Screenshots</a></li><liid="future"><ahref="future.aspx"title="Future">Future</a></li><liid="news"><ahref="news.aspx"title="News">News</a></li><liid="download"><ahref="download.aspx"title="Download">Download</a></li><liid="home"><ahref="index.aspx"title="Home">Home</a></li><liclass="forcePadding"><imgsrc="css/site-style-images/menu_corner_left.jpg" /></li></ul>
in the code-behind:
foreach(Control ctrl in nav.controls)
{
if(!ctrl is HtmlAnchor)
{
string url = ((HtmlAnchor)ctrl).Href;
if(url == GetCurrentPage()) // <-- you'd need to write that
ctrl.Parent.Attributes.Add("class", "active");
}
}
Solution 2:
The code below can be used to find a named control anywhere within the control hierarchy:
publicstatic Control FindControlRecursive(Control rootControl, string id)
{
if (rootControl != null)
{
if (rootControl.ID == id)
{
return rootControl;
}
for (int i = 0; i < rootControl.Controls.Count; i++)
{
Control child;
if ((child = FindControlRecursive(rootControl.Controls[i], id)) != null)
{
return child;
}
}
}
returnnull;
}
So you could do something like:
Control foundControl= FindControlRecursive(Page.Master, "theIdOfTheControlYouWantToFind");
((HtmlControl)foundControl).Attributes.Add("class", "active");
Forgot to mention previously, that you do need runat="server" on any control you want to be able to find in this way =)
Solution 3:
Add runat="server" on the li tags in the masterpage then add this to the appropriate page_load event to add the 'active' class to the li in the masterpage
HtmlGenericControl li = HtmlGenericControl)Page.Master.FindControl("screenshots"); li.Attributes.Add("class", "active");
Solution 4:
You could register a client script like this:
(set id to the id of the li that you want to set to active)
ClientScript.RegisterStartupScript(this.GetType(), "setActiveLI", "document.getElementById(\""+id+"\").setAttribute(\"class\", \"active\");", true);
This generates a JavaScript call on the page near the bottom after elements have already been rendered.
Solution 5:
All the parts have already been provided in previous answers, but to put the whole thing together, you'll need to:
<ul>
and <li>
elements
Alternatively you could also add the code to the OnLoad(...) method of the master page, so you don't have to add the method call to the Page_Load on every page.
Post a Comment for "C# - How To Change Html Elements Attributes"