SharePoint 2010 context menu item with custom code

List items in SharePoint lists and document libraries have a “context menu” on the Filename/FileLeafRef field. When you hover to the right of the field, you see a drop down menu with a bunch of options. You can add your own items to this list, and also run custom code when the item is clicked. This tutorial will show you how, using Visual Studio 2010 and SharePoint 2010.

Edit: 16/02/2012 – there were a few comments about the custom assembly not firing. I’ve revised the post below to include an extra bit in the XML to ensure the control loads (see #13.)

In SharePoint terminology, the context menu on a list item is called the EditControlBlock. We can create a CustomAction to add an item to the EditControlBlock. It can be added to four different types: Content Type, List, ProgID or File Type. In this example, we will attach to a Content Type. More info on the types.

1. In Visual Studio, create a new empty SharePoint project, called SPTest.CustomMenuItem. Use your local SharePoint site to debug, and deploy as a Farm Solution.

2. Right-click your new project, and go Add > New Item. Choose Empty Element, and name it ContextMenuItem.

3. Add the following XML within the Elements section:

<CustomAction Id="SPTest.CustomMenuItem.ButtonClicked"
                RegistrationType="ContentType"
                RegistrationId="0x0101"
                Location="EditControlBlock"
                ImageUrl="/_layouts/IMAGES/DOCLINK.GIF"
                Sequence="600"
                Title="Click Me!"
                Description="Shows an alert message for this content type."
                >
    <UrlAction Url="javascript:alert('Hello World!');" />
 </CustomAction>

4. This is actually all you need to create a custom menu item. This will be attached to documents of Content Type Document and any documents that inherit from document! Neat. To attach to other types, or your custom content types, change the RegistrationId attribute. Hint: to find the ID of a content type, find it in Site Settings > Site Content Types and click to view. The ID is in the URL bar.

5. Right-click your project and Deploy. Open up your SharePoint site, find a document that is using the specified Content Type, and open the context menu. You should see your new button:

6. And when clicked:

Well, Hello World is great and all, but how do you actually make it do something useful, like run some custom code? Let’s see. This will just write out a file with something in it, but obviously your code could do moreorless whatever you want.

7. Back in Visual Studio, add an empty C# (or VB!) Class to your Project. Call it CustomItemAction. Add a reference to System.Web.

8. Update your code to inherit from SPLinkButton and a few other bits:

using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SPTest.CustomMenuItem
{
    public class CustomItemAction : SPLinkButton
    {
                protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (this.Page.Request["__EVENTTARGET"] == "SPTest.CustomMenuItem.ButtonClicked")
            {
                int itemId = Convert.ToInt32(this.Page.Request["__EVENTARGUMENT"]);

                System.IO.TextWriter writer = new StreamWriter(@"C:\\custommenuoutput.txt", true);

                writer.WriteLine("Event Fired at:" + DateTime.Now.ToLongTimeString() + ": Item ID:" + itemId.ToString());

               writer.Close();

            }

        }
    }
}

9. Now – Deploy your project again. This won’t actually work yet, but we need to get some info in order to wire up our CustomAction to our custom class.

10. On the machine, navigate to C:\Windows\assembly. In the items, find SPTest.CustomMenuItem. View the properties of it, and note/copy the Public Key Token.

11. We can now link our CustomAction to our Class. In Elements.xml file, add the following attributes:

ControlAssembly="SPTest.CustomMenuItem, Version=1.0.0.0, Culture=neutral, PublicKeyToken={PublicKeyToken}"
                ControlClass="SPTest.CustomMenuItem.CustomItemAction" 

Replace {PublicKeyToken} with the token you noted down from the assembly.

12. We also need to update the UrlAction to send a Postback, to trigger the event.

<UrlAction Url="javascript:__doPostBack('SPTest.CustomMenuItem.ButtonClicked',{ItemId});" />

13. We also need to tell SharePoint to load the control:

<Control
ControlAssembly="SPTest.CustomMenuItem, Version=1.0.0.0, Culture=neutral, PublicKeyToken={PublicKeyToken}"
                ControlClass="SPTest.CustomMenuItem.CustomItemAction" Sequence="50" Id="AdditionalPageHead"/>

14. Your finished Elements.xml file should look like this:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Control
ControlAssembly="SPTest.CustomMenuItem, Version=1.0.0.0, Culture=neutral, PublicKeyToken={PublicKeyToken}"
                ControlClass="SPTest.CustomMenuItem.CustomItemAction" Sequence="50" Id="AdditionalPageHead"/>
<CustomAction Id="SPTest.CustomMenuItem.ButtonClicked"
                RegistrationType="ContentType"
                RegistrationId="0x0101"
                Location="EditControlBlock"
                ImageUrl="/_layouts/IMAGES/DOCLINK.GIF"
                Sequence="600"
                Title="Click Me!"
                Description="Writes out a file..."
ControlAssembly="SPTest.CustomMenuItem, Version=1.0.0.0, Culture=neutral, PublicKeyToken={PublicKeyToken}"
                ControlClass="SPTest.CustomMenuItem.CustomItemAction" 
                >
<UrlAction Url="javascript:__doPostBack('SPTest.CustomMenuItem.ButtonClicked',{ItemId});" />
 </CustomAction>
</Elements>

15. One last thing…! Since we have a custom control, we need to tell SharePoint that it’s safe to load by updating the web.config. Navigate to your IIS folder for your web site, (usually C:\inetpub\wwwroot\wss\VirtualDirectories\80) and open up web.config in notepad, or VS etc.

16. Search for the SafeControls element, and at the bottom of the block, add:

<SafeControl Assembly="SPTest.CustomMenuItem, Version=1.0.0.0, Culture=neutral, PublicKeyToken={PublicKeyToken}" Namespace="SPTest.CustomMenuItem" TypeName="*" Safe="True" SafeAgainstScript="False" />

Again, replace {PublicKeyToken} with your specific token. Save the file.

17. Deploy your SharePoint project.

18. Restart IIS and SharePoint Admin Service.

19. Now when you click your custom button, it should create a file in the root of C: called custommenuoutput.txt with the ID of the item you passed in.

And that’s it! Hope you enjoyed this – any issues, please add a comment.

Some credit…

This post was galvanised from info from here which showed how to add the button, not the custom code, and here, which showed how to use the custom code, but note that you don’t actually need a “dummy” CustomAction – you can handle it just fine from the first one.



Tags: , , , ,

58 Responses to “SharePoint 2010 context menu item with custom code”

  1. Thanks, works beautifully.
    I received a 403 error but that was just because of user permissions didn’t allow me to write in the C:\ (Just logging it in case somebody else runs into the same issue)

  2. Ronald Kors says:

    Thanks for the code.

    In my solution i want to place the elements and c# file in a folder named CustomActions. When i do this the code no longer works allthough the namespace doesn’t change. Do you know what I should alter to make it work again?

  3. the CustomAction has to be in a file called Elements.xml. you may also need to use a module to deploy the files. see here for some sample: http://www.sharepointchick.com/archive/2010/03/26/deploying-a-custom-master-page-in-sharepoint-2010.aspx

  4. AJ says:

    it might be stupid but where can i get the PublicToken of my dll?

  5. It’s only a stupid question because the post already covers how to do that:

    10. On the machine, navigate to C:\Windows\assembly. In the items, find SPTest.CustomMenuItem. View the properties of it, and note/copy the Public Key Token.

  6. After having successfully run this from SharePoint 2010, I’m trying it out on SharePoint 2013 and it deploys fine, the ECB link is added yet the post back is never called in my class; did anybody get this to work for SharePoint 2013?

  7. Jaya says:

    Hi,

    I am unable to add the button in Displaytoolbar but I can add to EditControlBlock.
    Please let me know why I am unable to do.

    Thanks in Advance

  8. If you mean the Ribbon then that’s different. There’s another post here about that.

Leave a Reply