0

I'm creating a menu based on the user using the following code

            System.Text.StringBuilder sb = new StringBuilder();
            sb.AppendLine("<ul>");
            if (!Page.IsPostBack)
            {
                foreach (DataRow row in datatable.Rows)
                {

                     sb.AppendLine(String.Format("<li><a href= x.aspx?Name={0}&Short={1}&Long={2}></a></li>",
                     HttpUtility.UrlEncode(row["x_name"].ToString()),
                     HttpUtility.UrlEncode(row["x_short_name"].ToString()),
                     HttpUtility.UrlEncode(row["x_long_name"].ToString()),
                     row["x_short_name"].ToString()));

When the user selects an item from the menu the page is loaded using a querystring.
What i need to do is to give the item selected from the menu a class so that it can be set to active.

Not sure how to go about this. Thanks in advance

3
Contributors
3
Replies
36
Views
2 Years
Discussion Span
Last Post by ggamble
0

Hi

You can check your query string parameter to see if it matches one of the items in the list that is about to be appended to the StringBuilder and if it is, add the class attribute.

The following is an example that I created based on your concept, but will need modifying to meet your exact requirements:

    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("<ul>");
        if (!Page.IsPostBack)
        {
            foreach (DataRow row in datatable.Rows)
            {
                List<Object> stringArgs = new List<Object>() 
                {
                    HttpUtility.UrlEncode(row["x_name"].ToString()),
                    HttpUtility.UrlEncode(row["x_short_name"].ToString()),
                    HttpUtility.UrlEncode(row["x_long_name"].ToString())                   
                };
                if (Request.QueryString["Name"] != null && Request.QueryString["Name"].ToString() == HttpUtility.UrlEncode(row["x_name"].ToString()))
                {
                    string classString = " class=" + @"""yourclass""";
                    stringArgs.Add(classString);
                    sb.AppendLine(String.Format("<li><a href=x.aspx?Name={0}&Short={1}&Long={2}{3}>Click here</a></li>", stringArgs.ToArray()));
                }
                else
                {
                    sb.AppendLine(String.Format("<li><a href=x.aspx?Name={0}&Short={1}&Long={2}>Click here</a></li>", stringArgs.ToArray()));
                }
            }
            sb.AppendLine("</ul>");
            listDiv.InnerHtml = sb.ToString();
        }
    }

HTH

0

Use jQuery

$("ul.nav > li a[href*='pageName']").parent("ul.nav > li").addClass("active");

Edited by ggamble

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.