Create custom verbs for SharePoint 2010 web parts

Home | SharePoint Development | Create custom verbs for SharePoint 2010 web parts

The web part verbs are the menus items (like Minimize, Close etc) appears when we click the Edit option in web parts. The SharePoint web part framework exposes one of the propery called WebPartVerbCollection. This is very flexible which allows us to add our own items (custom web part verbs) to the web part collection.

The whole idea is to override the getter of WebPartVerbCollection property, add custom verb items and return it back to web part framework. The following code snippet covers the same.

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace WP_Verb_Sample.VisualWebPart1
{
    [ToolboxItemAttribute(false)]
    public class VisualWebPart1 : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/WP_Verb_Sample/VisualWebPart1/WPVerbSample.ascx";

        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);
        }

        public override WebPartVerbCollection Verbs
        {
            get
            {
                //return base.Verbs;

                WebPartVerb Verb1 = new WebPartVerb("Verb Inovking Server Handler", 
                                              new WebPartEventHandler(CustomVerbEventHandler));
                Verb1.Text = "Verb Inovking Server";
                Verb1.Description = "This verb is used to demonstrate the server-side WP verb operation";


                WebPartVerb Verb2 = new WebPartVerb("Verb Inovking Client Script", 
                                              "Javascript:alert("Hi from Client");");
                Verb2.Text = "Verb Inovking client script";
                Verb2.Description = "This verb is used to demonstrate the client-side WP verb operation";


                WebPartVerb[] addedVerbs = new WebPartVerb[] { Verb1, Verb2 };

                return new WebPartVerbCollection(base.Verbs, addedVerbs);


            }
        }




        protected void CustomVerbEventHandler(object sender, WebPartEventArgs args)
        {
            // any arbitrary operation can be performed here
           
            
        }
    }
}

The web part verbs can invoke both a client-side action and a server-side handler as well. The above sample covers both the scenarios. Once you compile and deploy this code, you’d see your custom webpart verb.

clip_image002

 Subscribe to my blog

One thought on “Create custom verbs for SharePoint 2010 web parts

Leave a Reply