[RESOLVED]Access an element from the code behind

I am trying to apply css class on the li element depending on the  url

How can I access all li elements. Do I have to access the ul and then  loop through the li elements?

In my loop I also want to compare the href property

Thanks

<div id ="navigation">
				<ul>
					<li>
						<a href="Home.aspx">Home</a>
					</li>
					<li>
						<a href="AllRecipes.aspx">A to Z Recipes</a>
					</li>
					<li>
						<a href="featured.aspx">Featured Recipes</a>
					</li>
					<li>
						<a href="videos.aspx">Videos</a>
					</li>
					<li>
						<a href="about.aspx">About</a>
					</li>
					<li >
						<a class ="submitRecipe" href="Submit.aspx">Submit recipe</a>
					</li>
				</ul>
			</div>

For standard html controls you need to add runat="server" to access the control from code behind; Also set an id. 

Generally, if you want to access a particular element from your code-behind, you could simply add an ID attribute along with a runat="server" attribute to each of your particular elements :

<ul>
    <li>
	<a id="Home" runat="server" href="Home.aspx">Home</a>
    </li>
    <li>
	<a id="Recipes" runat="server" href="AllRecipes.aspx">A to Z Recipes</a>
    </li>
    <li>
	<a id="Featured" runat="server" href="featured.aspx">Featured Recipes</a>
    </li>
    <li>
	<a id="Videos" runat="server" href="videos.aspx">Videos</a>
    </li>
    <li>
	<a id="About" runat="server" href="about.aspx">About</a>
    </li>
    <li >
	<a id="Submit" runat="server" class ="submitRecipe" href="Submit.aspx">Submit recipe</a>
    </li>
</ul>

This will allow you to access these elements within your code-behind directly (by their ID values) so you could add the following in your Page_Load event for each of your pages to target the appropriate one :

// In the Page_Load event of your AllRecipes.aspx page
Recipes.Attributes["class"] = "yourCssClass";

There are a variety of ways to handle this and it will just depend on exactly how you want to use it.

If you want to do this from code-behind, you need to convert the links to server controls. You can do this by adding runat=server and providing each one with a unique ID, or by using HyperLink controls. Taking the second option, you can access the href via
the NavigateUrl property.

Thank you

Leave a Reply