How to add links with query string to Quick Links/Current Navigation using code

In SharePoint 2010 you will find that you can add links with query string to Quick Links (aka Current Navigation) using the UI without any issue. If you enter something like http://mySite/pages/myPage.aspx?key=abc into the dialog, then it’d happily accept it.

If you tried doing this by code however, you may find that the link is saved, but the query string is removed. To achieve this with code, you will need to add a key to the link’s Properties bag after it has been created. Below is the code for doing this.

using (var site = new SPSite("http://mySite"))
{
    using (var web = site.OpenWeb())
    {
        var newNode = new SPNavigationNode("My Link", "pages/myPage.aspx");
        newNode = web.Navigation.QuickLaunch.AddAsFirst(newNode);
        newNode.Properties.Add("NodeType", "AuthoredLinkPlain");
        newNode.Properties.Add("UrlQueryString", "key=abc");
        newNode.Update();
    }
}

The magic key is UrlQueryString.

Note that when you add a link as the top level link by code, it will default to the Heading type. To add it as the Link type, you will need to add the NodeType key to the Properties bag. I have written about this here.

If you examine the Properties bag of an existing link added via the UI, you will find other interesting keys, such as the target for the link.

Advertisement

About Bernado

Based in Australia, I am a freelance SharePoint and Dynamics CRM developer. I love developing innovative solutions that address business and everyday problems. Feel free to contact me if you think I can help you with your SharePoint or CRM implementation.
This entry was posted in SharePoint. Bookmark the permalink.

1 Response to How to add links with query string to Quick Links/Current Navigation using code

  1. Gluttony says:

    Hi Bernardo,

    thank you for the tip ! It saved my day. I used it for Sharepoint 2013 though. I was having troubles when I was setting the URL of a link containing a query string, the query string was getting repeated N times.
    But doing that with PS as you explained worked perfectly for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s