Search code examples
c#selectmenumaster-pagessitemap

Select a menu item from Master Page


I currently have an asp Menu Control which loads a SiteMapDataSource in my Master Page. One of the site map nodes is "Tools" which opens a general "Tools.aspx" content page.

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode url="~/Default.aspx" title="Home"  description="">
    <siteMapNode url="Tools.aspx" title="Tools"  description="" />
  </siteMapNode>
</siteMap>

The "Tools.aspx" page contains an image button that takes the user to another content page "Translator.aspx". When navigating to this page the "Tools" menu item is no longer selected. My question is, how can I select the "Tools" menu item from the master page, within the "Translator.aspx" page?

I have tried the following method within the "Translator.aspx" page load:

protected void Page_Load(object sender, EventArgs e)
{
    //check if logged in
    if (!Page.IsPostBack)
    {
        Menu mp_Menu = (Menu)Page.Master.FindControl("mnuMaster");

        foreach (MenuItem mi in mp_Menu.Items)
        {
            if (mi.Text == "Tools")
            {
                mi.Selected = true;
            }
        }

    }
}

This does not work and it appears that 0 menu items are returned.

Would really appreciate it if someone could shed some light on this issue.


Solution

  • I solved this by entering the following code in the Master Page:

    protected void mnuMaster_MenuItemDataBound(object sender, MenuEventArgs e)
        {
            if (Session["Translator"] != null)
            {
                if (mnuMaster.Items.Count > 0)
                {
                    foreach (MenuItem mi in mnuMaster.Items)
                    {
                        if (mi.Text == "Tools")
                        {
                            mi.Selected = true;
                            Session["Translator"] = null;
                        }
                    }
                }
            }
        }
    

    I then added the following to the "Translator.aspx" page:

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Session["Translator"] = "true";
            }
        }
    

    I don't think this is the ideal solution but it worked for me.